无法将图像从 url 保存到磁盘

Saving image from url to disk not working

我正在尝试从我的应用程序中的 url 下载图像,以便 Today Extension 可以使用它。

所以我调用了[self downloadImageFromUrl:imageOne];,它使用了这个方法:

- (void)downloadImageFromUrl:(NSString *)url {
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];

    AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
    [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSURL *storeUrl = [fileManager containerURLForSecurityApplicationGroupIdentifier:@"group.myapp.TodayExtensionDefaults"];
        NSString *path = [storeUrl absoluteString];
        path = [path stringByAppendingPathComponent:@"Test/imageOne.png"];

        NSLog(@"Path is %@", path);

        NSLog(@"Response: %@", responseObject);
        UIImage *image = responseObject;

        [UIImagePNGRepresentation(image) writeToFile:path atomically:YES];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Image error: %@", error);
    }];

    [requestOperation start];
}

所以当我 运行 这个时,一切都执行得很好。我没有错误。然而,当我转到模拟器中登录的文件夹时,没有文件存在。我从写入操作中得到的错误是 Write returned error: The operation couldn’t be completed. (Cocoa error 4.)。所以我将写操作更改为:

if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
    NSError *error = nil;
    if (![[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error]) {
        NSLog(@"Error: %@. %s, %i", error.localizedDescription, __PRETTY_FUNCTION__, __LINE__);
    }
}

[UIImagePNGRepresentation(image) writeToFile:path options:NSDataWritingAtomic error:&error];

但我还是得到了Write returned error: The operation couldn’t be completed. (Cocoa error 4.)

您正在获取 absoluteString(其中包括方案等):

NSString *path = [storeUrl absoluteString];

我相信你想要 path:

NSString *path = [storeUrl path];