2015-09-22 16 views
13

Tôi cố gắng để ghi dữ liệu vào một tập tin với đoạn mã sau trong một khối hoàn cho NSURLSessionDownloadTask:Lỗi: Các tập tin ... không tồn tại khi gọi writeToFile trên 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]); 
       } 
    } 

tôi có thể hiển thị các hình ảnh tải về trong UIImageViews và kiểm tra null của tôi trên imageData tương tự như vậy xác nhận nó không phải là null. Tuy nhiên, khi tôi cố gắng ghi dữ liệu vào một tập tin, Mỹ NSLog in ra các lỗi sau chỉ ra rằng write failed:

(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"}} 

tôi đã không thể tìm thấy một câu hỏi khác về SO cho thấy thông báo lỗi này cho tệp này và tôi đang tìm thông báo lỗi khá phản trực giác. Lỗi của tôi ở đâu?

+0

Hãy thử sử dụng API tệp liên quan chứ không phải là những URL liên quan đến một. Hoặc ít nhất hãy kiểm tra những gì '[saveLocation absolutString]' là và nếu thư mục tồn tại. – trojanfoe

+0

@trojanfoe tại sao API có liên quan đến tệp tốt hơn? – helloB

+0

Vì đó là một giá trị liên quan đến tệp mà bạn muốn tạo kết quả (để cung cấp cho 'writeToFile:'). – trojanfoe

Trả lời

37

Thay vì [saveLocation absoluteString], hãy sử dụng [saveLocation path]. Về cơ bản, trước đây cung cấp cho bạn "file: /// path/filename" trong khi sau này cung cấp cho bạn "/ path/filename", đó là định dạng đúng.

+1

Bạn không có ý tưởng bao nhiêu thời gian tôi đã dành trên này. Cảm ơn bạn rất nhiều bro. – atulkhatri

5

Got Woking .. Cảm ơn bạn @superstart đang nhanh chóng dưới đây:

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); 
    } 
} 
Các vấn đề liên quan