在iOS应用程序和WatchKit扩展之间共享Plist
我有一个应用程序可以保存和使用plist文件中的数据。我正在开发一个WatchKit扩展,它需要访问相同的plist文件来显示数据并保存到文件中。我知道我需要使用应用程序组,但我不知道如何在iOS应用程序和WatchKit扩展之间共享plist 下面是我当前如何在iOS应用程序中保存到plist的在iOS应用程序和WatchKit扩展之间共享Plist,ios,objective-c,watchkit,ios-app-group,Ios,Objective C,Watchkit,Ios App Group,我有一个应用程序可以保存和使用plist文件中的数据。我正在开发一个WatchKit扩展,它需要访问相同的plist文件来显示数据并保存到文件中。我知道我需要使用应用程序组,但我不知道如何在iOS应用程序和WatchKit扩展之间共享plist 下面是我当前如何在iOS应用程序中保存到plist的 NSFileManager *fileManager = [NSFileManager defaultManager]; NSArray *paths = NSSearchPathForDir
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [[paths objectAtIndex:0]stringByAppendingPathComponent:@"locations.plist"];
BOOL fileExists = [fileManager fileExistsAtPath:docPath];
NSError *error = nil;
if (!fileExists) {
NSString *strSourcePath = [[NSBundle mainBundle]pathForResource:@"locations" ofType:@"plist"];
[fileManager copyItemAtPath:strSourcePath toPath:docPath error:&error];
}
NSString *path = docPath;
NSMutableArray *plistArray = [[NSMutableArray alloc]initWithContentsOfFile:path];
NSDictionary *locationDictionary = [NSDictionary dictionaryWithObjectsAndKeys:self.locationNameTextField.text, @"locationName", latString, @"latitude", longString, @"longitude", nil];
[plistArray insertObject:locationDictionary atIndex:0];
[plistArray writeToFile:docPath atomically:YES];
设置应用程序组(在主iPhone应用程序和Watch扩展程序中)后,您可以获得共享文件夹的路径:
NSURL *groupContainerURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"YourAppGroupSuiteName"];
NSString *groupContainerPath = [groupContainerURL path];
然后可以使用
groupContainerPath
构建docPath
。否则,您的代码应该按原样工作。我能够使用Swift在我的WatchKit应用程序中成功地使用我现有的主要iPhone应用程序中的plist数据
有两个步骤:
func valueFromPlist(值:Int,文件:String)->String?{
如果让plistpath=NSBundle.mainBundle().pathForResource(文件为字符串,类型为“plist”){
如果let entries=NSArray(contentsOfFile:plistpath)作为数组{
var entry=Dictionary()
输入{
如果让id=entry.objectForKey(“id”)作为?Int{
如果id==值{
如果让name=entry.objectForKey(“name”)作为?字符串{
返回名称
}
}
}
}
}
}
归零
}
func valueFromPlist(value: Int, file: String) -> String? {
if let plistpath = NSBundle.mainBundle().pathForResource(file as String, ofType: "plist") {
if let entries = NSArray(contentsOfFile: plistpath) as Array? {
var entry = Dictionary<String, Int>()
for entry in entries {
if let id = entry.objectForKey("id") as? Int {
if id == value {
if let name = entry.objectForKey("name") as? String {
return name
}
}
}
}
}
}
return nil
}