Подтвердить что ты не робот

Ошибка: файл... не существует при вызове writeToFile на imageData

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

4b9b3361

Ответ 1

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

Ответ 2

Got Woking.. Спасибо @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);
    }
}

Ответ 3

У вас может быть проблема с промежуточным каталогом, который не существует. Если какие-либо подкаталоги (папки) не существуют при записи файла, произойдет сбой.

Вот удобная функция для создания единого каталога с любым именем в папке документов. Если вы попытаетесь написать это после запуска, все должно быть в порядке.

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