I have an app that saves and uses data from a plist file. I'm working on a WatchKit extension that needs to access the same plist file to display data and save to the file. 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.
Here is how I'm saving to the plist in the iOS app currently.
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:
NSURL *groupContainerURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"YourAppGroupSuiteName"];
NSString *groupContainerPath = [groupContainerURL path];
You can then use the groupContainerPath
to build your 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.
There are two steps:
Here's the Swift code I used to read the plist, which has "id" and "name" fields.
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 }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.