从文档目录中获取图像而不是文件路径 Swift 3 [英] Get images from Document Directory not file path Swift 3

查看:17
本文介绍了从文档目录中获取图像而不是文件路径 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)

        }

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

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

推荐答案

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

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

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

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.

如果您有一个装满图片的文件夹,您可以在该文件夹上迭代以取回 img 文件:

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

这篇关于从文档目录中获取图像而不是文件路径 Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆