Get images from Document Directory not file path Swift 3

时光毁灭记忆、已成空白 提交于 2019-12-25 08:48:31

问题


This is how I saved the images

    let format = DateFormatter()
    format.dateFormat="MMMM-dd-yyyy-ss"
    let currentFileName = "\(format.string(from: Date())).img"
    print(currentFileName)

    // Save Images
    let fileMgr = FileManager.default
    let dirPath = fileMgr.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let imageFileUrl = dirPath.appendingPathComponent(currentFileName)



        do {

            try UIImagePNGRepresentation(returnedImages)!.write(to: imageFileUrl)

            print("Image Added Successfully")

    } catch {

        print(error)

        }

Below is code I am using to retrieve images, But I am getting the URL instead of the image file to populate tableview. Any help would be appreciated

   let fileManager = FileManager.default
   let imageUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask) [0].appendingPathComponent("img")

   print("Your Images:\(imageUrl)")

回答1:


It's simply because your image's name is invalid. Use the debugger to find the exact value of imageUrl, I bet it's something like this .../Documents/img. What you want is more like .../Documents/Sep-04-2017-12.img

You'd have to store currentFileName in the view controller so you can reference it later.

Also, your naming strategy is pretty fragile. Many images can end up sharing one name.


If you have a folder full of images, you can iterate on that folder to get back the img files:

let fileManager = FileManager.default
let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
let directoryContents = try! fileManager.contentsOfDirectory(at: documentDirectory, includingPropertiesForKeys: nil)
for imageURL in directoryContents where imageURL.pathExtension == "img" {
    if let image = UIImage(contentsOfFile; imageURL.path) {
        // now do something with your image
    } else {
       fatalError("Can't create image from file \(imageURL)")
    }
}



回答2:


Try using this

 func getImage(){
        let fileManager = FileManager.default
        let imagePAth = (self.getDirectoryPath() as NSString).appendingPathComponent("apple.jpg") // saved image name apple.jpg
        if fileManager.fileExists(atPath: imagePAth){
            self.lockbackImageview.image = UIImage(contentsOfFile: imagePAth)
        }else{
            print("No Image")
            self.lockbackImageview.image = UIImage.init(named: "1.jpg")
        }
    }


来源:https://stackoverflow.com/questions/46045948/get-images-from-document-directory-not-file-path-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!