如何从文件目录保存和加载图像-Swift 4

时间:2019-02-06 15:14:48

标签: ios swift nsfilemanager

我正在尝试将图像保存到文件目录并从文件目录加载图像,但是我的writeImageToPath函数将以下错误打印到控制台,并说该文件不存在。

控制台

  

将图片写入目录

     

文件存在写入图像

     

错误   将图像写入目录   文件不存在-file:/// Users / user / Library / Developer / CoreSimulator / Devices / 70EAC77D-9F3C-4AFC-8CCA-A7B9B895BDE6 / data / Containers / Data / Application / DDAF2EBD-5DDA-4EA6-95D3-6785B74A0B09 / Documents / upload / http://i.annihil.us/u/prod/marvel/i/mg/a/f0/5202887448860-可供使用   写图片   “写入图像时出错:Error Domain = NSCocoaErrorDomain代码= 4”文件“ 5202887448860”不存在。” UserInfo = {NSFilePath = / Users / user / Library / Developer / CoreSimulator / Devices / 70EAC77D-9F3C-4AFC-8CCA-A7B9B895BDE6 / data / Containers / Data / Application / DDAF2EBD-5DDA-4EA6-95D3-6785B74A0B09 / Documents / upload / http://i.annihil.us/u/prod/marvel/i/mg/a/f0/5202887448860,NSUnderlyingError = 0x600003b04ab0 {Error Domain = NSPOSIXErrorDomain代码= 2“没有这样的文件或目录”}}

这是我的代码,我不确定我要去哪里哪里

// The images are loaded from the web and displayed in the cell.imageView.image

  if let thumbnail = product["thumbnail"] as? [String: Any],
     let path = thumbnail["path"] as? String,
     let fileExtension = thumbnail["extension"] as? String {

  //Save image to directory
  if image != nil {
     writeImageToPath(path, image: image!)
  }

  }


// Write image to directory
func writeImageToPath(_ path: String, image: UIImage) {
    print("Write image to directory")

    let uploadURL = URL.createFolder(folderName: "upload")!.appendingPathComponent(path)

    if !FileManager.default.fileExists(atPath: uploadURL.path) {
        print("File does NOT exist -- \(uploadURL) -- is available for use")

        let uploadURL = URL.createFolder(folderName: "upload")!.appendingPathComponent(path)

        if let data = UIImageJPEGRepresentation(image, 0.9) {
            do {
                print("Write image")
                try data.write(to: uploadURL)
            }
            catch {
                print("Error Writing Image: \(error)")
            }

        } else {
            print("Image is nil")
        }
    } else {
        print("This file exists -- something is already placed at this location")
    }

}


// load image from directory
func loadImageFromPath(_ path: String) -> UIImage? {

    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]

    let folderURL = documentsURL.appendingPathComponent("upload")

    let fileURL = folderURL.appendingPathComponent(path)

    if FileManager.default.fileExists(atPath: fileURL.path) {
        //Get Image And upload in server
        print("fileURL.path \(fileURL.path)")

        do{
            let data = try Data.init(contentsOf: fileURL)
            let image = UIImage(data: data)
            return image
        }catch{
            print("error getting image")
        }
    } else {
        print("No image in directory")
    }

    return nil
}


extension URL {
static func createFolder(folderName: String) -> URL? {
    let fileManager = FileManager.default
    // Get document directory for device, this should succeed
    if let documentDirectory = fileManager.urls(for: .documentDirectory,
                                                in: .userDomainMask).first {
        // Construct a URL with desired folder name
        let folderURL = documentDirectory.appendingPathComponent(folderName)
        // If folder URL does not exist, create it
        if !fileManager.fileExists(atPath: folderURL.path) {
            do {
                // Attempt to create folder
                try fileManager.createDirectory(atPath: folderURL.path,
                                                withIntermediateDirectories: true,
                                                attributes: nil)
            } catch {
                // Creation failed. Print error & return nil
                print(error.localizedDescription)
                return nil
            }
        }
        // Folder either exists, or was created. Return URL
        return folderURL
    }
    // Will only be called if document directory not found
    return nil
}
}

如何正确保存和加载目录中的图像?

3 个答案:

答案 0 :(得分:1)

class MyImageClass {
    func writeImageToPath(_ path:String, image:UIImage) {
        let uploadURL = URL.createFolder(folderName: "upload")!.appendingPathComponent(path)

        if !FileManager.default.fileExists(atPath: uploadURL.path) {
            print("File does NOT exist -- \(uploadURL) -- is available for use")
            let data = image.jpegData(compressionQuality: 0.9)
            do {
                print("Write image")
                try data!.write(to: uploadURL)
            }
            catch {
                print("Error Writing Image: \(error)")
            }
        }
        else {
            print("This file exists -- something is already placed at this location")
        }
    }
}

extension URL {
    static func createFolder(folderName: String) -> URL? {
        let fileManager = FileManager.default
        // Get document directory for device, this should succeed
        if let documentDirectory = fileManager.urls(for: .documentDirectory,
                                                in: .userDomainMask).first {
            // Construct a URL with desired folder name
            let folderURL = documentDirectory.appendingPathComponent(folderName)
            // If folder URL does not exist, create it
            if !fileManager.fileExists(atPath: folderURL.path) {
                do {
                    // Attempt to create folder
                    try fileManager.createDirectory(atPath: folderURL.path,
                                                withIntermediateDirectories: true,
                                                attributes: nil)
                } catch {
                    // Creation failed. Print error & return nil
                    print(error.localizedDescription)
                    return nil
                }
            }  
            // Folder either exists, or was created. Return URL
            return folderURL
        }
        // Will only be called if document directory not found
        return nil
    }
}

var saving = MyImageClass()
saving.writeImageToPath("whereIWantToSaveTheImageTo", image: UIImage(named: "myImage"))

参考 Create Directory in Swift 3.0

我没有测试映像是否工作,但是,这确实创建了一个名为“上传”的文件夹,您可以每次调用它。该扩展名有一个名为createFolder的方法,该方法将为您调用的任何文件返回一个文件夹,并在该文件夹尚未创建时创建它。我们只需要检查文件夹中的指定路径,然后就可以对其进行写操作了。我也只重写了writeImageToPath部分。

注意:

在操场上进行了测试...

结果是:

File does NOT exist -- file:///var/folders/vs/nlj__xh93vs0f8wzcgksh_zh0000gn/T/com.apple.dt.Xcode.pg/containers/com.apple.dt.playground.stub.iOS_Simulator.MyPlayground-67A67A07-51FF-4DF4-BE80-02E7FDAFA1CA/Documents/upload/whereIWantToSaveTheImageTo -- is available for use
Write image

答案 1 :(得分:0)

使用正确的路径名替换此函数调用的路径名错误

writeImageToPath("http://i.annihil.us/u/prod/marvel/i/mg/b/70/4c0035adc7d3a", image: image)

收件人

writeImageToPath("4c0035adc7d3a", image: image)

答案 2 :(得分:0)

下面是如何将图像保存到名为“ Screenshots”的文件夹中。我尽力使它保持清晰。

func saveImageToDocumentDirectory(image: UIImage) {
    var objCBool: ObjCBool = true
    let mainPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0];
    let folderPath = mainPath + "/Screenshots/"

    let isExist = FileManager.default.fileExists(atPath: folderPath, isDirectory: &objCBool)
    if !isExist {
        do {
            try FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
        } catch {
            print(error)
        }
    }

    let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let imageName = "\(fileName).png"
    let imageUrl = documentDirectory.appendingPathComponent("Screenshots/\(imageName)")
    if let data = image.jpegData(compressionQuality: 1.0){
        do {
            try data.write(to: imageUrl)
        } catch {
            print("error saving", error)
        }
    }
}

这就是我加载存储在文件夹中的图像的方式

 func loadImageFromDocumentDirectory(nameOfImage : String) -> UIImage {
    let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
    let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
    let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
    if let dirPath = paths.first{
        let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("Screenshots/\(nameOfImage)")
        guard let image = UIImage(contentsOfFile: imageURL.path) else { return  UIImage.init(named: "fulcrumPlaceholder")!}
        return image
    }
    return UIImage.init(named: "imageDefaultPlaceholder")!
}