Ошибка при сохранении изображения в каталоге документов - PullRequest
0 голосов
/ 12 марта 2019

Я получаю URL изображения с моего сервера, который я хочу сохранить в каталоге документов. Но в моем следующем коде я получаю сообщение об ошибке.

вот мой путь к файлу URL - file:///var/mobile/Containers/Data/Application/7AA1BEDE-DA10-4BD6-8115-06C9DCA53BF2/Documents/https://www.cocubes.com/images/getimage.aspx%3Ft=l&id=602

Файл URL.path = /var/mobile/Containers/Data/Application/7AA1BEDE-DA10-4BD6-8115-06C9DCA53BF2/Documents/https://www.cocubes.com/images/getimage.aspx?t=l&id=602

'?' конвертируется в% 3F, из-за чего, я думаю (не уверен), я не могу перейти на нужный путь. Как решить эту проблему ??

static func saveImageInDocsDir(image: UIImage,urlString: NSString) {
    let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    // choose a name for your image
    //let fileName = "image.jpg"
    // create the destination file url to save your image
    let fileURL = documentsDirectory.appendingPathComponent(urlString as String)
    print(fileURL)
    print(fileURL.path)
    // get your UIImage jpeg data representation and check if the destination file url already exists
    if let data = image.jpegData(compressionQuality: 1.0),
        !FileManager.default.fileExists(atPath: fileURL.path) {
        do {
            // writes the image data to disk
            try data.write(to: fileURL)
            print("file saved")
        } catch {
            print("error saving file:", error)
        }
    }
}

Ответы [ 2 ]

0 голосов
/ 12 марта 2019

Проблема в том, что urlString содержит /, FileManager пытается сохранить данные изображения в несуществующей папке. Это можно исправить, заменив вхождения символа / на _.

let fileURL = documentsDirectory.appendingPathComponent((urlString as String).replacingOccurrences(of: "/", with: "_"))

Другое решение - сначала создать папку.

static func saveImageInDocsDir(image: UIImage, urlString: NSString) {
    let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    // choose a name for your image
    //let fileName = "image.jpg"
    // create the destination file url to save your image
    let fileURL = documentsDirectory.appendingPathComponent(urlString as String)
    print(fileURL)
    print(fileURL.path)
    // get your UIImage jpeg data representation and check if the destination file url already exists
    if let data = image.jpegData(compressionQuality: 1.0),
        !FileManager.default.fileExists(atPath: fileURL.path) {
        do {
            // First create a directory
            try FileManager.default.createDirectory(at: fileURL.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: nil)
            // writes the image data to disk
            try data.write(to: fileURL)
            print("file saved")
        } catch {
            print("error saving file:", error)
        }
    }
}
0 голосов
/ 12 марта 2019

Пожалуйста, добавьте эту строку ниже: let filePath = documentsDirectory.appendingPathComponent (fileURL)

 static func saveImageInDocsDir(image: UIImage,urlString: NSString) {
                let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
                // choose a name for your image
                //let fileName = "image.jpg"
                // create the destination file url to save your image
                let fileURL = documentsDirectory.appendingPathComponent(urlString as String)
                print(fileURL)
                print(fileURL.path)
                // get your UIImage jpeg data representation and check if the destination file url already exists
                let filePath = documentsDirectory.appendingPathComponent(fileURL)
                if let data = image.jpegData(compressionQuality: 1.0),
                    !FileManager.default.fileExists(atPath: filePath.path) {
                    do {
                    // writes the image data to disk
                    try data.write(to: fileURL)
                    print("file saved")
                    } catch {
                    print("error saving file:", error)
                }
        }
    }
...