Get image from documents directory swift

后端 未结 4 658
清酒与你
清酒与你 2020-11-27 13:43

Say I were using this code to save an image to the documents directroy

let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask         


        
4条回答
  •  不知归路
    2020-11-27 14:26

    You are finding the document directory path at runtime for writing the image, for reading it back, you can use the exact logic:

    Swift 3 and 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
    }
    

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

提交回复
热议问题