Get images from Document Directory not file path Swift 3

后端 未结 2 1619
夕颜
夕颜 2021-01-28 00:04

This is how I saved the images

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


        
相关标签:
2条回答
  • 2021-01-28 00:44

    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)")
        }
    }
    
    0 讨论(0)
  • 2021-01-28 00:58

    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")
            }
        }
    
    0 讨论(0)
提交回复
热议问题