常见使用场景1:APP之间数据共享(如账号登录)
常见使用场景2:容器APP与扩展应用之间资源共享(如:iMessage、keyboard等)
一、认识App Groups
AppGroup allows data sharing between two different apps or even app and widgets by creating one common shared path (like document directory). Data saved over there can be accessed by any app which is associated with that particular AppGroup. It is an offline data sharing between apps.
这段苹果说明告诉我们:App Groups可以使两个不同的APP(或者APP与其Extension)之间进行数据共享。
二、配置APP Groups
-
在Apple Developer中配置APP的App ID时,勾选AppGroups选项:
勾选AppGroups.png -
创建APP Groups:
创建AppGroups.png
这个id默认是要group.打头,并且是不能去掉的。常用命名方法是:'group.'+BundleID。
-
将APP Groups添加到APP ID中。回到步骤1创建的APP ID那里,可以看到APP Groups选项为黄色待编辑状态,点击Edit将步骤2创建的APP Groups添加进去:
添加AppGroups到APP ID.jpeg -
将APP Groups添加到Xcode工程中:
AppGroups工程配置.png
添加完成之后将在项目中生成一个xxx.entitlements文件(这其实就是一个xml配置文件,事实上日后如果添加其他服务如Push Notifications,其配置也会添加到这个文件中)
三、APP Group在项目中的使用
App Groups支持的常用数据共享包括NSUserDefaults、NSFileManager、NSFileCoordinator、NSFilePresenter、UIPasteboard、KeyChain、NSURLSession等。
下边以NSUserDefaults和NSFileManager为例:
生成数据部分
#pragma mark - NSUserDefaults
- (void)setAppGroup1
{
NSUserDefaults *myDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.test.appgroup"];//此处id要与开发者中心创建时一致
[myDefaults setObject:@"value" forKey:@"key"];
NSLog(@"%@", [myDefaults valueForKey:@"key"]);
}
#pragma mark - NSFileManager
- (void)setAppGroup2{
//获取分组的共享目录
NSURL *groupURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.test.appgroup"];//此处id要与开发者中心创建时一致
NSURL *fileURL = [groupURL URLByAppendingPathComponent:@"demo.txt"];
//写入文件
[@"abc" writeToURL:fileURL atomically:YES encoding:NSUTF8StringEncoding error:nil];
//读取文件
NSString *str = [NSString stringWithContentsOfURL:fileURL encoding:NSUTF8StringEncoding error:nil];
NSLog(@"str = %@", str);
}
获取共享数据部分
#pragma mark - NSUserDefaults
- (void)getByAppGroup1
{
NSUserDefaults *myDefaults = [[NSUserDefaults alloc]initWithSuiteName:@"group.test.appgroup"];//此处id要与开发者中心创建时一致
NSString *content = [myDefaults objectForKey:@"key"];
NSLog(@"%@",content);
}
#pragma mark - NSFileManager
- (void)getByAppGroup2{
//获取分组的共享目录
NSURL *groupURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.test.appgroup"];//此处id要与开发者中心创建时一致
NSURL *fileURL = [groupURL URLByAppendingPathComponent:@"demo.txt"];
//读取文件
NSString *str = [NSString stringWithContentsOfURL:fileURL encoding:NSUTF8StringEncoding error:nil];
NSLog(@"str = %@", str);
}
参考链接:
https://www.jianshu.com/p/94d4106b9298
https://www.jianshu.com/p/aa6f4f41d6e3
https://www.cnblogs.com/kenshincui/p/5644803.html
网友评论