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

Get images from Document Directory not file path Swift 3

我是这样保存图片的

    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)

        }

下面是我用来检索图像的代码,但我得到的是 URL 而不是图像文件来填充表格视图。任何帮助将不胜感激

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

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

这是因为您的图片名称无效。使用调试器找到 imageUrl 的确切值,我打赌它是这样的 .../Documents/img。你想要的更像是.../Documents/Sep-04-2017-12.img

您必须将 currentFileName 存储在视图控制器中,以便稍后引用它。

此外,您的命名策略非常脆弱。许多图像最终可以共享一个名称。


如果您有一个装满图像的文件夹,您可以迭代该文件夹以取回 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)")
    }
}

试试这个

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