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

hel*_*loB 15 objective-c ios

我试图在完成块中使用以下代码将数据写入文件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]);
                }
     }
Run Code Online (Sandbox Code Playgroud)

我能够显示下载的图像,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"}} 
Run Code Online (Sandbox Code Playgroud)

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

sup*_*org 43

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

  • 你不知道我花了多少时间在这个上面.非常感谢兄弟. (3认同)

pau*_*l_f 6

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

这是在文档文件夹中创建任何名称的单个目录的一个方便的功能。如果您在运行后尝试写入它应该没问题。

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)
        }
    }
Run Code Online (Sandbox Code Playgroud)


Ant*_*eph 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);
    }
}
Run Code Online (Sandbox Code Playgroud)