IOS 兩個或多個App文件數(shù)據(jù)共享方法App Groups

數(shù)據(jù)共享有很多種,大部分好心人都已經(jīng)寫了。這里我就借用一下鏈接。
iOS應(yīng)用程序間共享數(shù)據(jù)

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獲取這個目錄,再讀取共享的文件,然后該干哈就干哈。
最后上代碼下載地址
代碼下載地址

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,351評論 25 708
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,697評論 19 139
  • Ubuntu的發(fā)音 Ubuntu,源于非洲祖魯人和科薩人的語言,發(fā)作 oo-boon-too 的音。了解發(fā)音是有意...
    螢火蟲de夢閱讀 100,831評論 9 468
  • 想撿起一直都希望練就的繪畫本領(lǐng),做完線條練習(xí)后,畫下桌上擺著的小盆栽。 植物生長的線條只有在沉心畫畫時才能感受到,...
    小小小毛毛閱讀 115評論 0 0
  • 2018.3.21 3.21補卡 英語聽力半小時,英語跟讀 陪孩子寫作業(yè) 其實是兩周的落差體現(xiàn)在了周三
    灸灸微笑閱讀 74評論 0 0

友情鏈接更多精彩內(nèi)容