iOS学习笔记-APP之间数据共享空间AppGroups

文章目录

  • 创建AppGroups
  • 项目中配置
  • 代码中使用
    • NSUserDefaults
    • NSFileManager
    • CoreData使用
    • AppGroupManager

APP之间共享数据的方式约以下几种:

  1. URL Scheme 跳转
  2. App Groups 共享一块存储空间
  3. KeyChain共享数据(keychain access group) 账号密码共用,不会随App删除
  4. UIDocumentInteractionController 文档分享,例如文件在QQ中打开的功能
  5. 粘贴板UIPasteboard 复制粘贴

App Groups 用于两个app之间共享文件,开扩了一块共同的存储区域

此外扩展( Extension )也需要使用App Groups 的相关知识

此方法只能使用于同一个开发者账号,如果不同开发者账号请考虑剪切板 UIPasteboard

若需要存储共有的账号密码,请使用KeyChain

创建AppGroups

登陆开发者账号
https://developer.apple.com/account/
选择Certificates,IDS & Profiles
iOS学习笔记-APP之间数据共享空间AppGroups_第1张图片
选择Identifiers,添加一个
iOS学习笔记-APP之间数据共享空间AppGroups_第2张图片

选择App Groups

然后填写描述和group标识
在这里插入图片描述
然后 continue

每个app id需要打开App Groups功能,并配置好


项目中配置

打开你的xcode项目工程,先选中根目录,在target中选中你的工程–>Capabilites

iOS学习笔记-APP之间数据共享空间AppGroups_第3张图片


代码中使用

NSUserDefaults

//初始化一个供App Groups使用的NSUserDefaults对象
NSUserDefaults *userDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.company.appGroupName"];

//写入数据
[userDefaults setValue:@"value" forKey:@"key"];

//读取数据
NSLog(@"%@", [userDefaults valueForKey:@"key"]);

NSFileManager

//获取分组的共享目录
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]方式取到


CoreData使用

//获取分组的共享项目
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类,如需要可以使用:


AppGroupManager

  • AppGroupManager.h
//
//  AppGroupManager.h
//  MHJFamilyV1
//
//  Created by tangmi on 16/8/4.
//  Copyright © 2016年 mhjmac. All rights reserved.
//

#import 

@interface AppGroupManager : NSObject

///your apple appgroup id   eg:"com.company.testname"
@property (nonatomic, copy) NSString *identifier;

///appgroup file's url
@property (nonatomic, strong) NSURL *url;

#pragma init
///singleton method
+ (instancetype)defaultManager;
///init
- (instancetype)initWithGroupIdentifier:(NSString*)group;

#pragma write normal data - string dic data array
///写入jsonStr字符串到Json文件中
- (BOOL)writeToFile:(NSString *)filename withJson:(NSString *)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
///copy file
- (BOOL)saveDataFromPath:(NSString *)originPath toFile:(NSString *)filename;
///根据data类型写入对应类型的文件中
- (BOOL)saveData:(NSData *)data toFile:(NSString *)filename;
///get data (image,file...) from "(appgroup url)/filename"
- (NSData *)dataFromFile:(NSString *)filename;
///delete File
- (BOOL)deleteFile:(NSString *)filename;

#pragma read
///read json string from file that name is filename
- (NSString *)jsonFromFile:(NSString *)filename;
///as same as upon, just turn string to dictionary
- (NSDictionary *)dictionaryFormFile:(NSString *)filename;


#pragma other
///judge file is exist;
- (BOOL)isExistFile:(NSString *)filename;

@end

  • AppGroupManager.m
//
//  AppGroupManager.m
//  MHJFamilyV1
//
//  Created by tangmi on 16/8/4.
//  Copyright © 2016年 mhjmac. All rights reserved.
//

#import "AppGroupManager.h"

static NSString * const mhjgroup = @"group.company.appGroupName";  //默认的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]) {
        _identifier = group;
        _url = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier: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{
        //文件不存在
        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];
    
}

@end

使用的话应该以AppGroupManager为工具再封装一层使用于自己项目逻辑的类

网盘链接: https://pan.baidu.com/s/10QwSQGbtuBeH0HRg5ZkG9g 密码: uki7

你可能感兴趣的:(iOS学习笔记,iOS开发)