Iam*_*yne 0 nsdocumentdirectory swift swift3 xcode8
这就是我保存图像的方式
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)
}
Run Code Online (Sandbox Code Playgroud)
下面是我用来检索图像的代码,但是我正在获取URL而不是图像文件来填充tableview。任何帮助,将不胜感激
let fileManager = FileManager.default
let imageUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask) [0].appendingPathComponent("img")
print("Your Images:\(imageUrl)")
Run Code Online (Sandbox Code Playgroud)
仅仅是因为您的图片名称无效。使用调试器查找的确切值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)")
}
}
Run Code Online (Sandbox Code Playgroud)