[英]Share Plist between iOS App and WatchKit Extension
I have an app that saves and uses data from a plist file. 我有一个应用程序,可以保存和使用plist文件中的数据。 I'm working on a WatchKit extension that needs to access the same plist file to display data and save to the file.
我正在开发一个WatchKit扩展,需要访问相同的plist文件来显示数据并保存到文件中。 I know I need to be using app groups but I don't know how to share the plist between the iOS app and the WatchKit extension.
我知道我需要使用应用程序组,但我不知道如何在iOS应用程序和WatchKit扩展程序之间共享plist。
Here is how I'm saving to the plist in the iOS app currently. 这是我目前在iOS应用程序中保存到plist的方式。
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];
Once you've setup your app group (in both your primary iPhone app and the Watch Extension), you can get the path to the shared folder: 设置应用程序组后(在主iPhone应用程序和Watch Extension中),您可以获取共享文件夹的路径:
NSURL *groupContainerURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"YourAppGroupSuiteName"];
NSString *groupContainerPath = [groupContainerURL path];
You can then use the groupContainerPath
to build your docPath
. 然后,您可以使用
groupContainerPath
构建docPath
。 Otherwise, your code should work as-is. 否则,您的代码应该按原样运行。
I was able to successfully use plist data from my main existing iPhone app in my WatchKit app using Swift. 我能够使用Swift在我的WatchKit应用程序中成功使用来自我现有主要iPhone应用程序的plist数据。
There are two steps: 有两个步骤:
Here's the Swift code I used to read the plist, which has "id" and "name" fields. 这是我用来读取plist的Swift代码,它有“id”和“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 }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.