iOS extension与host App共享数据

在制作iOS extension时通常需要从host App中获取一些数据 获取的方法是使用App Group

因为Ghost放图不太方便 就尽量用文字描述清楚了

  1. 首先是分别在"Target -> host app(extension) -> General -> Identity"设置Bundle ID
    通常host APP跟extension的bundle id分别是这样

    appName.companyName

    appName.companyName.extensionName

  2. 在host app跟extension分别开启APP Groups
    “Targets -> host app(extension) -> Capabilities -> APP Groups"

  3. 在步骤2同位置添加APP Groups id (取个好记的)

  4. 用下面Demo的方法写入/读取数据

写入:

    NSUserDefaults *mySharesDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.YourGroupID"];
    NSData* dataFromArray = [NSKeyedArchiver archivedDataWithRootObject:myArray];
        [mySharesDefaults setObject:dataFromArray forKey:@"myStorageKey"];
    [mySharesDefaults synchronize];

读取:

    NSUserDefaults *mySharesDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.YourGroupID"];
    NSData* someData = [mySharesDefaults objectForKey:@"myStorageKey"];
    NSArray* unzip = [NSKeyedUnarchiver unarchiveObjectWithData:someData];