1. 程式人生 > >iOS學習筆記-APP之間資料共享空間_APPGroup

iOS學習筆記-APP之間資料共享空間_APPGroup

appgroup用於兩個app之間共享檔案,開擴了一塊共同的儲存區域!

此外擴充套件( Extension )也需要使用appgroup的相關知識

此方法只能使用於同一個開發者賬號,如果不同開發者賬號請考慮剪下板 UIPasteboard

1.建立APPGroup

1.登入開發者賬號

點選APPGroup那欄:這裡寫圖片描述

右上方新增APPGroup:

這裡寫圖片描述

然後確認就行了

2.專案中配置

開啟你的xcode專案工程,先選中根目錄,在target中選中你的工程–>Capabilites

這裡寫圖片描述

3.程式碼中使用

1.NSUserDefaults

//初始化一個供App Groups使用的NSUserDefaults物件
NSUserDefaults *userDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.company.appGroupName"]; //寫入資料 [userDefaults setValue:@"value" forKey:@"key"]; //讀取資料 NSLog(@"%@", [userDefaults valueForKey:@"key"]);

2.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]方式取到

3.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
//  MHJFamilyV1
//
//  Created by tangmi on 16/8/4.
//  Copyright © 2016年 mhjmac. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface AppGroupManager : NSObject

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

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

#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;

@end

//
//  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]) {
        self = [[AppGroupManager alloc]init];
        self.identifier = group;
        self.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{

        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];

}

@end


使用的話應該以AppGroupManager為工具再封裝一層使用於自己專案邏輯的類