进程间通信-App Groups

最简单的进程间的数据共享App Groups
此事例对应屏幕共享数据传输、使用时请酌情处理

App Groups创建

创建

按顺序点击


新建及选择

哪些应用需要共享同一份数据就把他们的App Groups设置成同一个


扩展中使用

那么数据要怎么保存和使用呢?

数据读写1_UserDefaults

//读取
-(void)getDataWithUserDefaults{
    //初始化一个供App Groups使用的NSUserDefaults对象
    NSUserDefaults *userDefaults = [[NSUserDefaults standardUserDefaults] initWithSuiteName:@"group.tongxun_xiaolang"];
    NSLog(@"%@", [userDefaults valueForKey:@"buffer"]);
}
//写入
- (void)saveNSDataWithUserDefaults:(NSData*)data{
    NSUserDefaults *shared = [[NSUserDefaults standardUserDefaults]     initWithSuiteName:@"group.tongxun_xiaolang"];
    [shared setObject:data forKey:@"buffer"];
    [shared synchronize];
}

数据读写2_FileManager

//读取
-(void)getDataWithFileManager{
    NSError *err = nil;
    NSURL *containerURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.tongxun_xiaolang"];
    containerURL = [containerURL URLByAppendingPathComponent:@"Library/Caches/data"];
    NSString *value = [NSString stringWithContentsOfURL:containerURL encoding:NSUTF8StringEncoding error:&err];
    NSData *data = [value dataUsingEncoding:NSUTF8StringEncoding];

    if (err != nil) {
        NSLog(@"xxxx %@",err);
        return;
    }
    NSLog(@"----%@",data);
}
//写入
- (void)saveNSDataWithFileManager:(NSData*)data{
    NSError *err = nil;
    NSURL *containerURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.tongxun_xiaolang"];
    containerURL = [containerURL URLByAppendingPathComponent:@"Library/Caches/data"];
    NSString *dataString = [[NSString alloc] initWithData:data encoding:kCFStringEncodingUTF8];
    [dataString writeToURL:containerURL atomically:YES encoding:NSUTF8StringEncoding error:&err];
}
CMSampleBufferRef转NSData
- (NSData *)dataWithSampBuffer:(CMSampleBufferRef)sampBuffer { CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampBuffer);
    CVPixelBufferLockBaseAddress(imageBuffer,0);
    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
    size_t width = CVPixelBufferGetWidth(imageBuffer);
    size_t height = CVPixelBufferGetHeight(imageBuffer);
    void *src_buff = CVPixelBufferGetBaseAddress(imageBuffer);
    NSData *data = [NSData dataWithBytes:src_buff length:bytesPerRow * height];
    CVPixelBufferUnlockBaseAddress(imageBuffer, 0);
    return data;
}

你可能感兴趣的:(进程间通信-App Groups)