简体   繁体   中英

Sharing Data Between iOS App and Todays Extension

I have an iOS app which uses on-device database. I want to access the database from my App Extension. The database access requires a path which I insert into the NSUserDefaults as shown below. I first run the App Target which triggers the following code.

 NSUserDefaults *userDefaults = [[NSUserDefaults alloc] init];
    [userDefaults setValue:databasePathFromApp forKey:@"DatabasePath"];
    [userDefaults synchronize];

Then I run the Todays Extension which accesses the NSUserDefaults set by the Main App.

 NSUserDefaults *userDefaults = [[NSUserDefaults alloc] init];

    _databasePath = [userDefaults valueForKey:@"DatabasePath"];

The _databasePath is always nil. What am I doing wrong? Do I have to use App Groups to share database between the app and the todays extension.

You should use NSUserDefaults like this following and make sure you must have enabled app group in your provisional profile and app group must configure as a green symbol and it should add to your provisional profile & BundleID.

NSUserDefaults *sharedUserDefault = [[NSUserDefaults alloc] initWithSuiteName:@"group.yougroup"]; [sharedUserDefault setObject:object forKey:@"yourkey"]; [sharedUserDefault synchronize];

NSUserDefaults *sharedUserDefault = [[NSUserDefaults alloc] initWithSuiteName:@"group.yougroup"]; sharedUserDefault value = [sharedUserDefault valueForKey:@"yourkey"];

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