// 主APP,增删改数据,保存到NSUserDefaults
NSUInteger numberOfItemsSnapshot = MIN(self.mutArray.count, 4);
NSArray<NSString *> *snapshot = [self.mutArray subarrayWithRange:NSMakeRange(self.mutArray.count - numberOfItemsSnapshot, numberOfItemsSnapshot)];
NSUserDefaults *groupDefault = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.dcj.DCJExtension"];
[groupDefault setObject:snapshot forKey:@"TodaySnapshot"];
// APP Extension,当用户查看时,加载数据,创建UI
- (void)loadContents
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSUserDefaults *groupDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.dcj.DCJExtension"];
self.contentArray = [groupDefaults objectForKey:@"TodaySnapshot"];
dispatch_async(dispatch_get_main_queue(), ^{
if (self.contentArray.count == 0) {
[self showEmptyPlaceholder];
}else
{
self.bTianJia.hidden = YES;
self.tableView.hidden = NO;
self.preferredContentSize = CGSizeMake(0, self.contentArray.count * 44 -1);
[self.tableView reloadData];
}
});
});
}
// 在Extension,打开容器APP
[self.extensionContext openURL:[NSURL URLWithString:@"DCJExtension://new_item"] completionHandler:nil];
// 需要在容器APP的info里,做如下配置
// 从Extension,直接到主程序,完成一些事。容器APP在此方法中,响应外部APP或者Extension的打开。
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
if ([url.relativeString hasPrefix:@"DCJExtension://new_item"]) {
[[NSNotificationCenter defaultCenter] postNotificationName:kRequestNewItemNote object:nil];
}
return YES;
}
参考http://www.jianshu.com/p/bbc6a95d9c54
http://www.cocoachina.com/ios/20170706/19749.html