2015-09-22 3 views
13

Я пытаюсь записать данные в файл со следующим кодом в блоке завершения для NSURLSessionDownloadTask:Ошибка: Файл ... не существует при вызове WriteToFile на ImageData

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 также подтверждает, что это не null. Однако, когда я пытаюсь записать данные в файл, My 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 указывает на это сообщение об ошибке для этот файл, и я нахожу сообщение об ошибке довольно противоречивым. Где моя ошибка?

+0

Попробуйте использовать File API, связанных, а не те, что URL связанных друг. Или, по крайней мере, проверьте, что '[saveLocation absolutString]' есть, и если каталог существует. – trojanfoe

+0

@trojanfoe почему API, связанный с файлами, лучше? – helloB

+0

Потому что это значение, связанное с файлом, которое вы хотите в результате (чтобы дать 'writeToFile:'). – trojanfoe

ответ

37

Вместо [saveLocation absoluteString], используйте [saveLocation path]. По сути, первый дает вам «файл: /// путь/имя файла», в то время как последний дает вам «/ path/filename», который является правильным форматом.

+1

Вы не представляете, сколько времени я потратил на это. Большое вам спасибо. – atulkhatri

5

Got Уокинг .. Спасибо @superstart быстрый код ниже:

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); 
    } 
}