一尘不染

从文档目录快速获取图像

swift

说我正在使用此代码将图像保存到Directroy文档中

let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) {
if paths.count > 0 {
    if let dirPath = paths[0] as? String {
        let readPath = dirPath.stringByAppendingPathComponent("Image.png")
        let image = UIImage(named: readPath)
        let writePath = dirPath.stringByAppendingPathComponent("Image2.png") 
        UIImagePNGRepresentation(image).writeToFile(writePath, atomically: true)
    }
  }
}

那我该如何找回呢?请记住,与iOS8相比,确切的路径经常更改


阅读 185

收藏
2020-07-07

共1个答案

一尘不染

您可以在运行时找到用于写入图像的文档目录路径,以便读取图像,可以使用确切的逻辑:

Swift 3和Swift 4.2

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("Image2.png")
   let image    = UIImage(contentsOfFile: imageURL.path)
   // Do whatever you want with the image
}

迅捷2

let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask    = NSSearchPathDomainMask.UserDomainMask
if let paths            = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
{
     if paths.count > 0
     {
         if let dirPath   = paths[0] as? String
         {
             let readPath = dirPath.stringByAppendingPathComponent("Image2.png")
             let image    = UIImage(contentsOfFile: readPath)
             // Do whatever you want with the image
         }
     }
}
2020-07-07