ios - 错误 : The file. ..在 imageData 上调用 writeToFile 时不存在

标签 ios objective-c

我正在尝试在 NSURLSessionDownloadTask 的完成 block 中使用以下代码将数据写入文件:

   void (^completionBlock)(NSURLResponse *response, NSURL *filePath, NSError *error) = ^void (NSURLResponse *response, NSURL *filePath, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!error){
                NSData *imageData = [NSData dataWithContentsOfURL:filePath];
                if(imageData) NSLog(@"image is not null");

                if(pic == 1) self.imageView.image = [UIImage imageWithData:imageData];
                else if(pic==2) self.imageView2.image = [UIImage imageWithData:imageData];

                NSArray *paths = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
                NSURL *documentsDirectoryURL = [paths lastObject];
                NSURL *saveLocation;
                if(pic == 1) saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:self.pictureName1];
                else if (pic == 2) saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:self.pictureName2];
                else saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:self.pictureName3];

                NSLog(@"for # %d writing to file %@", pic, saveLocation);

                NSError *error = nil;                
                [imageData writeToFile:[saveLocation absoluteString] options:NSAtomicWrite error: &error];
                if(error){
                    NSLog(@"FAILED\n\n\n %@ \n\n\n", [error description]);
                }
     }

我能够在 UIImageViews 中显示下载的图像,并且我对 imageData 的空检查同样确认它不为空。但是,当我尝试将数据写入文件时,我的 NSLog 打印出以下错误,表明写入失败:

(log statements)
# 3 writing to file file:///var/mobile/Containers/Data/Application/3743A163-7EE1-4A5A-BF81-7D1344D6DA45/Documents/pic3.png
Error Domain=NSCocoaErrorDomain Code=4 "The file “pic1.jpg” doesn’t exist." 
UserInfo={NSFilePath=file:///var/mobile/Containers/Data/Application/3743A163-7EE1-
4A5A-BF81-7D1344D6DA45/Documents/pic1.jpg, NSUnderlyingError=0x16d67200 {Error
Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}} 

我没能在 SO 上找到另一个问题,指出此文件的此错误消息,而且我发现错误消息非常违反直觉。我的错误在哪里?

最佳答案

使用 [saveLocation path] 代替 [saveLocation absoluteString]。基本上前者给你“file:///path/filename”,而后者给你“/path/filename”,这是正确的格式。

关于ios - 错误 : The file. ..在 imageData 上调用 writeToFile 时不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32716895/

相关文章:

ios - watch 操作系统 : which icon is used in the MyWatch App

ios - Swift 2.0 中使用一个自定义动画类进行多个 Segues

objective-c - 在 UITableView 中加载本地 json 信息

ios - 关闭 ViewController 并能够使用相同的细节再次呈现/显示它 - 类似于 Spotify "player view"

ios - 使用 MVC 设计模式在 Storyboard 中正确使用 IBOutlets

ios - 检测 UITextView 上的点击仅检测取消

ios - 按钮上的 Xcode 在单独的 ViewController 上按下隐藏标签

ios - 如何从 GCD 返回 UIImage 类型

ios - 在纵向和横向中使用 AutoLayout

ios - uiwebview 即使有 delegate = self 也没有加载请求