appgroup用于两个app之间共享文件,开扩了一块共同的存储区域!
此外扩展( Extension )也需要使用appgroup的相关知识
此方法只能使用于同一个开发者账号,如果不同开发者账号请考虑剪切板 UIPasteboard
https://developer.apple.com/account/ios/certificate/development
右上方添加APPGroup:
然后确认就行了
打开你的xcode项目工程,先选中根目录,在target中选中你的工程–>Capabilites
//初始化一个供App Groups使用的NSUserDefaults对象
NSUserDefaults *userDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.company.appGroupName"];
//写入数据
[userDefaults setValue:@"value" forKey:@"key"];
//读取数据
NSLog(@"%@", [userDefaults valueForKey:@"key"]);
//获取分组的共享目录
NSURL *groupURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.company.appGroupName"];
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);
利用NSFileManager我们可以存取各种文件,数据库文件(.db),json文件,framework等等;我们可以复制各种文件到APPGroup的存取区域,在另一个app中拿出来
static NSString * const group = @"group.company.appGroupName";
- (BOOL)saveDataFromPath:(NSString *)originPath toFile:(NSString *)filename;
{
self.url = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:group];
NSURL *fileURL = [self.url URLByAppendingPathComponent:filename];
return [[NSFileManager defaultManager] copyItemAtPath:originPath toPath:[fileURL path] error:nil];
}
在第一块代码中,NSFileManager是以NSURL来操作的,同样,我们可以以path进行操作,这是没问题的,path可由URL的[fileURL path]方式取到
//获取分组的共享项目
NSURL *containerURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.cn.vimfung.ShareExtensionDemo"];
NSURL *storeURL = [containerURL URLByAppendingPathComponent:@"DataModel.sqlite"];
//初始化持久化存储调度器
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"DataModel" withExtension:@"momd"];
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
[coordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeURL
options:nil
error:nil];
//创建受控对象上下文
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[context performBlockAndWait:^{
[context setPersistentStoreCoordinator:coordinator];
}];
我没有深入用过,所以这里不做详细阐述;
另外添上封装的AppGroupManager类,如需要可以使用:
#import
@interface AppGroupManager : NSObject
@property (nonatomic, strong) NSString *identifier; //your apple appgroup id eg:"group.com.hyb.ms"
@property (nonatomic, strong) NSURL *url; //appgroup file's url
@property (nonatomic, strong) NSUserDefaults * userDefaultes;
#pragma init
+ (instancetype)defaultManager; //singleton method
- (instancetype)initWithGroupIdentifier:(NSString*)group; //init
#pragma write normal data - string dic data array
- (BOOL)writeToFile:(NSString *)filename withJson:(NSString *)jsonStr; //写入jsonStr字符串到Json文件中
- (BOOL)writeToFile:(NSString *)filename withDictionary:(NSDictionary *)dic; //同上 只是将字典转换成字符串存入
- (BOOL)writeToFile:(NSString *)filename withData:(NSData *)data;
- (BOOL)writeToFile:(NSString *)filename withArray:(NSArray *)array;
#pragma file
- (BOOL)saveDataFromPath:(NSString *)originPath toFile:(NSString *)filename; //copy file
- (BOOL)saveData:(NSData *)data toFile:(NSString *)filename; //根据data类型写入对应类型的文件中
- (NSData *)dataFromFile:(NSString *)filename; //get data (image,file...) from "(appgroup url)/filename"
- (BOOL)deleteFile:(NSString *)filename; //delete File
#pragma read
- (NSString *)JsonFromFile:(NSString *)filename; //read json string from file that name is filename
- (NSDictionary *)dictionaryFormFile:(NSString *)filename; //as same as upon, just turn string to dictionary
#pragma other
- (BOOL)isExistFile:(NSString *)filename; //judge file is exist;
#pragma - NSUserDefaults
#pragma -- save
- (BOOL)setObject:(nullable id)value forKey:(NSString *_Nullable)defaultName;
#pragma -- take out
- (nullable id)objectForKey:(NSString *_Nullable)defaultName;
#import "AppGroupManager.h"
static NSString * const mhjgroup = @"group.com.hyb.ms"; //默认的appgroup
@implementation AppGroupManager
#pragma mark init
static AppGroupManager *manager = nil;
+ (instancetype)defaultManager
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [[AppGroupManager alloc]initWithGroupIdentifier:mhjgroup];
});
return manager;
}
- (instancetype)initWithGroupIdentifier:(NSString*)group
{
if (self = [super init]) {
self = [[AppGroupManager alloc]init];
self.identifier = group;
self.url = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:group];
self.userDefaultes = [[NSUserDefaults alloc] initWithSuiteName:group];
}
return self;
}
#pragma mark write normal data - string dic data array
- (BOOL)writeToFile:(NSString *)filename withJson:(NSString*)jsonStr
{
NSURL *fileURL = [self.url URLByAppendingPathComponent:filename];
return [jsonStr writeToURL:fileURL atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
- (BOOL)writeToFile:(NSString *)filename withDictionary:(NSDictionary*)dic
{
NSString *jsonStr = [AppGroupManager dictionaryToJson:dic];
return [self writeToFile:filename withJson:jsonStr];
}
- (BOOL)writeToFile:(NSString *)filename withData:(NSData *)data
{
NSURL *fileURL = [self.url URLByAppendingPathComponent:filename];
return [data writeToURL:fileURL atomically:YES];
}
- (BOOL)writeToFile:(NSString *)filename withArray:(NSArray *)array
{
NSURL *fileURL = [self.url URLByAppendingPathComponent:filename];
return [array writeToURL:fileURL atomically:YES];
}
#pragma file save
- (BOOL)saveDataFromPath:(NSString *)originPath toFile:(NSString *)filename;
{
NSURL *fileURL = [self.url URLByAppendingPathComponent:filename];
return [[NSFileManager defaultManager] copyItemAtPath:originPath toPath:[fileURL path] error:nil];
}
- (BOOL)saveData:(NSData *)data toFile:(NSString *)filename
{
NSURL *fileURL = [self.url URLByAppendingPathComponent:filename];
return [[NSFileManager defaultManager] createFileAtPath:[fileURL path] contents:data attributes:nil];
}
- (NSData *)dataFromFile:(NSString *)filename
{
NSURL *fileURL = [self.url URLByAppendingPathComponent:filename];
return [[NSFileManager defaultManager] contentsAtPath:[fileURL path]];
}
- (BOOL)deleteFile:(NSString *)filename;
{
NSURL *fileURL = [self.url URLByAppendingPathComponent:filename];
return [[NSFileManager defaultManager] removeItemAtPath:[fileURL path] error:nil];
}
#pragma mark read
- (NSString*)JsonFromFile:(NSString *)filename
{
NSURL *fileURL = [self.url URLByAppendingPathComponent:filename];
BOOL isExist = [[NSFileManager defaultManager] isExecutableFileAtPath:[fileURL path]];
if (isExist) {
NSString *str = [NSString stringWithContentsOfURL:fileURL encoding:NSUTF8StringEncoding error:nil];
return str;
}else{
NSLog(@"文件不存在");
return nil;
}
}
- (NSDictionary *)dictionaryFormFile:(NSString *)filename
{
NSURL *fileURL = [self.url URLByAppendingPathComponent:filename];
NSString *str = [NSString stringWithContentsOfURL:fileURL encoding:NSUTF8StringEncoding error:nil];
if (str) {
return [AppGroupManager dictionaryWithJsonString:str];
}else{
return nil;
}
}
#pragma mark other
- (BOOL)isExistFile:(NSString *)filename;
{
NSURL *fileURL = [self.url URLByAppendingPathComponent:filename];
NSString *path = [fileURL path];
BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:path];
return isExist;
}
#pragma mark private methods
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
if (jsonString == nil) {
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err];
if(err) {
NSLog(@"json解析失败:%@",err);
return nil;
}
return dic;
}
+ (NSString*)dictionaryToJson:(NSDictionary *)dic
{
NSError *parseError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
#pragma NSUserDefaults
- (BOOL)setObject:(nullable id)value forKey:(NSString *_Nullable)defaultName
{
if (!value || !defaultName) return false;
[self.userDefaultes setObject:value forKey:defaultName];
return true;
}
- (nullable id)objectForKey:(NSString *_Nullable)defaultName
{
if (!defaultName) return nil;
return [self.userDefaultes objectForKey:defaultName];
}
@end