将图像从URL保存到磁盘不起作用

时间:2022-03-28 09:00:55

I'm trying to download an image from an url in my app, so that it can be used by the Today Extension.

我正在尝试从我的应用中的网址下载图片,以便今日推广可以使用它。

So I call [self downloadImageFromUrl:imageOne];, which uses this method:

所以我打电话给[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];
}

So when I run this, everything executes fine. I get no errors. Yet, when I go to the folder logged in the simulator, no file is present. The error I get from the write action is Write returned error: The operation couldn’t be completed. (Cocoa error 4.). And so I changed the write action to:

所以当我运行它时,一切都运行良好。我没有错。然而,当我转到模拟器中记录的文件夹时,没有文件存在。我从写入操作中得到的错误是写入返回错误:操作无法完成。 (可可错误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];

But I still get Write returned error: The operation couldn’t be completed. (Cocoa error 4.)

但我仍然得到Write返回错误:操作无法完成。 (可可错误4.)

1 个解决方案

#1


You are grabbing the absoluteString (which includes the scheme, amongst other things):

你正在抓住absoluteString(其中包括方案):

NSString *path = [storeUrl absoluteString];

I believe you intended the path:

我相信你想要的道路:

NSString *path = [storeUrl path];

#1


You are grabbing the absoluteString (which includes the scheme, amongst other things):

你正在抓住absoluteString(其中包括方案):

NSString *path = [storeUrl absoluteString];

I believe you intended the path:

我相信你想要的道路:

NSString *path = [storeUrl path];