简体   繁体   中英

Shared files between IOS app and watch extension

I have an IOS app with a watch extension. I use a read-only SQLite file with Core Data (which is already populated and not edited).

Accessing the file from the bundle resources works fine using this code.

- (NSURL *)storeURL{
    NSString * databaseFileName = @"db.sqlite";
    return  [NSURL fileURLWithPath: [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: databaseFileName]];
}

However, this code creates a new sqlite file and attach it to the NSPersistentStoreCoordinator:

- (NSURL *)applicationDocumentsDirectory {
    return [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.com.xxx.xxx"];
}

- (NSURL *)storeURL{
    NSString * databaseFileName = @"db.sqlite";

    NSURL * url = [self applicationDocumentsDirectory];
    NSString * path = [url.absoluteString stringByAppendingPathComponent:databaseFileName];

    path = [path stringByReplacingOccurrencesOfString:@"file:" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, path.length)];

    return [NSURL fileURLWithPath: path];
}

How do I add the SQLite file to a shared app group container in Xcode?

While that was possible in watchOS 1 (since the watch extension used to run on the iPhone), you can no longer use a shared app group to share a Core Data store between the iPhone and Apple Watch.

What you can do is include a copy of that read-only SQLite file in your watchOS app bundle, by adding it to the watch app's target. Then you can use your original storeURL code to add that store to the persistent store coordinator.

在此处输入图片说明

The only downside is that the distribution will be larger, since the embedded watch app now contains a separate copy of the SQLite file.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM