简体   繁体   English

从文档目录而不是文件路径获取图像Swift 3

[英]Get images from Document Directory not file path Swift 3

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. 下面是我用来检索图像的代码,但是我正在获取URL而不是图像文件来填充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)")

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 . 使用调试器查找imageUrl的确切值,我敢打赌,它类似于.../Documents/img What you want is more like .../Documents/Sep-04-2017-12.img 您想要的更像是.../Documents/Sep-04-2017-12.img

You'd have to store currentFileName in the view controller so you can reference it later. 您必须将currentFileName存储在视图控制器中,以便以后可以引用它。

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: 如果您的文件夹中充满了图像,则可以在该文件夹上进行迭代以获取img文件:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM