Search code examples
iosobjective-cwatchkitios-app-group

Share Plist between iOS App and WatchKit Extension


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];

Solution

  • 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.