IOS 两个或多个App文件数据共享方法App Groups

数据共享有很多种,大部分好心人都已经写了。这里我就借用一下链接。
iOS应用程序间共享数据

AppA写入端代码,很简单的,如下:

#import "ViewController.h"

#define APP_GROUP_ID        @"group.com.dacheng.AppGroupFileShare"
#define APP_FOLDER_NAME     @"DachengShareFile"


@interface ViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong)       NSString *storagePath;
@property (nonatomic, strong)       NSArray *fileNamesArray;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"主App共享File";
    [self writeFirstFileToShare];
    [self loadData];
}

- (void)writeFirstFileToShare
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    BOOL isOpened = [[defaults objectForKey:@"isOpened"] boolValue];
    if(!isOpened){
        [defaults setObject:@(YES) forKey:@"isOpened"];

        NSString *file1Cont = @"Hello every one. I'm M0nk1y. My site: http://mkapple.cn";
        NSString *file2Cont = @"new File2:";

        [file1Cont writeToFile:[self.storagePath stringByAppendingPathComponent:@"File1.text"] atomically:YES encoding:NSUTF8StringEncoding error:nil];
        [file2Cont writeToFile:[self.storagePath stringByAppendingPathComponent:@"File2.text"] atomically:YES encoding:NSUTF8StringEncoding error:nil];

        NSString *file3Path = [[NSBundle mainBundle] pathForResource:@"battery" ofType:@"sqlite"];
        NSString *file3ToPath = [self.storagePath stringByAppendingPathComponent:@"battery.sqlite"];
        NSError *error;
        BOOL success = [[NSFileManager defaultManager] copyItemAtPath:file3Path toPath:file3ToPath error:&error];
        NSLog(@"success:%d==error:%@", success, error);

    }
}

- (void)loadData
{
//    self.fileNamesArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self.storagePath error:nil];
//    for (NSString *fileName in self.fileNamesArray) {
//        NSString *path = [self.storagePath stringByAppendingPathComponent:fileName];
//        BOOL success = [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
//        NSLog(@"success:%d", success);
//    }
//    NSLog(@"self.fileNamesArray:%@", self.fileNamesArray);
    
    self.fileNamesArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self.storagePath error:nil];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.tableView reloadData];
    
    NSLog(@"self.fileNamesArray:%@", self.fileNamesArray);
}


#pragma mark - 获取共享容器文件夹路径
- (NSString *)storagePath
{
    if (_storagePath) {
        return _storagePath;
    }
    NSURL *groupURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:APP_GROUP_ID];
    NSString *groupPath = [groupURL path];
    self.storagePath = [groupPath stringByAppendingPathComponent:APP_FOLDER_NAME];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:_storagePath]) {
        [fileManager createDirectoryAtPath:_storagePath withIntermediateDirectories:NO attributes:nil error:nil];
    }
    return _storagePath;
}


#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.fileNamesArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.textLabel.text = self.fileNamesArray[indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSString *filePath = [self.storagePath stringByAppendingPathComponent:self.fileNamesArray[indexPath.row]];
    
    NSLog(@"filePath:%@", filePath);
    
    if (indexPath.row < 2) {
        NSString *fileContent = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
        NSLog(@"content:%@", fileContent);
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

AppB端读取代码,更简单,和上面代码基本一样。

#import "ViewController.h"

#define APP_GROUP_ID        @"group.com.dacheng.AppGroupFileShare"
#define APP_FOLDER_NAME     @"DachengShareFile"


@interface ViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong)       NSString *storagePath;
@property (nonatomic, strong)       NSArray *fileNamesArray;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"App从共享目录读取文件";
    [self loadData];
}


- (void)loadData
{
    self.fileNamesArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self.storagePath error:nil];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.tableView reloadData];
    
    NSLog(@"self.fileNamesArray:%@", self.fileNamesArray);
}


#pragma mark - 获取共享容器文件夹路径
- (NSString *)storagePath
{
    if (_storagePath) {
        return _storagePath;
    }
    NSURL *groupURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:APP_GROUP_ID];
    NSString *groupPath = [groupURL path];
    self.storagePath = [groupPath stringByAppendingPathComponent:APP_FOLDER_NAME];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:_storagePath]) {
        [fileManager createDirectoryAtPath:_storagePath withIntermediateDirectories:NO attributes:nil error:nil];
    }
    return _storagePath;
}


#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.fileNamesArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.textLabel.text = self.fileNamesArray[indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSString *filePath = [self.storagePath stringByAppendingPathComponent:self.fileNamesArray[indexPath.row]];
    
    NSLog(@"filePath:%@", filePath);
    
    if (indexPath.row < 2) {
        NSString *fileContent = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
        NSLog(@"content:%@", fileContent);
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

解释一下逻辑

通过打印共享文件路径可以得到如下:

/private/var/mobile/Containers/Shared/AppGroup/F4578610-A8D5-4221-A37C-6F12CFEE8AD4/DachengShareFile/File2.text

路径很明显,Shared共享目录AppGroup单独开辟一个地址
逻辑就是:
AppA把文件通过AppGroupID存放到这个目录
AppB再通过AppGroupID获取这个目录,再读取共享的文件,然后该干哈就干哈。
最后上代码下载地址
代码下载地址

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,457评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,408评论 19 139
  • Ubuntu的发音 Ubuntu,源于非洲祖鲁人和科萨人的语言,发作 oo-boon-too 的音。了解发音是有意...
    萤火虫de梦阅读 99,887评论 9 468
  • 想捡起一直都希望练就的绘画本领,做完线条练习后,画下桌上摆着的小盆栽。 植物生长的线条只有在沉心画画时才能感受到,...
    小小小毛毛阅读 669评论 0 0
  • 2018.3.21 3.21补卡 英语听力半小时,英语跟读 陪孩子写作业 其实是两周的落差体现在了周三
    灸灸微笑阅读 548评论 0 0