Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
93 views
in Technique[技术] by (71.8m points)

ios - Get image from documents directory swift

Say I were using this code to save an image to the documents 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)
    }
  }
}

How would I then retrive it? Keeping in mind than in iOS8 the exact path changes often

question from:https://stackoverflow.com/questions/29005381/get-image-from-documents-directory-swift

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...