无法写入 containerURLForSecurityApplicationGroupIdentifier?

Cannot write to containerURLForSecurityApplicationGroupIdentifier?

在下面的例子中,我写入没有错误,但是读取时,数据长度为0。为什么我不能写入共享容器?

+ (UIImage *)read {
    NSData *data = [NSData dataWithContentsOfFile:[self getPath]];
    NSLog(@"Data length: %d", data.length);
    UIImage *image = [UIImage imageWithContentsOfFile:[self getPath]];
    NSLog(@"%@", image);
    return image;
}

+ (void)write:(UIImage *)image {
    NSString *pngFilePath = [self getPath];
    NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
    [data1 writeToFile:pngFilePath atomically:YES];
}

+ (NSString *)getPath {
    NSURL *containerUrl = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.me.app"];
    NSString *pngFilePath = [[containerUrl absoluteString] stringByAppendingPathComponent:@"current.png"];

    NSLog(@"%@", pngFilePath);
    return pngFilePath;
}

您混淆了 URL 和文件路径。使用 [containerUrl path] 而不是 [containerUrl absoluteString],或者使用 dataWithContentsOfURL/writeToURL 而不是 dataWithContentsOfFile/writeToFile。