错误:在imageData上调用writeToFile时,文件...不存在

时间:2015-09-22 12:28:45

标签: ios objective-c

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

   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上找到另一个问题,指出此文件的此错误消息,并且我发现错误消息非常违反直觉。我的错误在哪里?

4 个答案:

答案 0 :(得分:42)

而不是[saveLocation absoluteString],请使用[saveLocation path]。基本上前者给你" file:/// path / filename"而后者为你提供" / path / filename",这是正确的格式。

答案 1 :(得分:5)

得到了Woking ..谢谢@superstart下面的swift代码:

let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first
let fileNameString = fileURL.absoluteString.stringByReplacingOccurrencesOfString("/", withString: "");
let destinationUrl = documentsUrl!.URLByAppendingPathComponent("check.m4a")

let request: NSURLRequest = NSURLRequest(URL: fileURL)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{ (response: NSURLResponse?, datas: NSData?, error: NSError?) in
    if error == nil
    {
       // datas?.writeToFile(destinationUrl.absoluteString, atomically: false);

        do
        {
            let result = try Bool(datas!.writeToFile(destinationUrl.path!, options: NSDataWritingOptions.DataWritingAtomic))
            print(result);
        }
        catch let errorLoc as NSError
        {
            print(errorLoc.localizedDescription)
        }
    }
    else
    {
        print(error?.localizedDescription);
    }
}

答案 2 :(得分:0)

您可能遇到的中间目录不存在的问题。如果编写文件时不存在任何子目录(文件夹),则它将失败。

这是在文档文件夹中创建任何名称的单个目录的便捷功能。如果您在运行此代码后尝试写此代码,那应该没问题。

static func createDirIfNeeded(dirName: String) {
        let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent(dirName + "/")
        do {
            try FileManager.default.createDirectory(atPath: dir.path, withIntermediateDirectories: true, attributes: nil)
        } catch {
            print(error.localizedDescription)
        }
    }

答案 3 :(得分:0)

要在项目名称文件夹下的“文件”应用程序上查看保存的文件,请对Info.plist启用以下权限

enter image description here