![](/img/trans.png)
[英]Can i load images from the device's documents directory to AsyncImageView?
[英]Can not load images from `Documents` directory on device
在模拟器上这是有效的。 这是我保存图像时打印的路径:
/var/mobile/Containers/Data/Application/31912F79-EB94-4DB1-84B8-68C7368B9160/Documents/t123t.jpg
这是 html 中的 img 标签,它应该将图像加载到 webView(在模拟器上运行良好):
img src="file:///var/mobile/Containers/Data/Application/31912F79-EB94-4DB1-84B8-68C7368B9160/Documents/t123t.jpg">
我可以看到这里一切正常,我认为问题应该出在路径上,我从img src
删除了部分file://
但它没有帮助我。
解决了
出于某种原因,无法通过从字符串加载 html 的方式访问Documents
中的图像。 我需要在Documents
文件夹中创建一个html file
才能从该文件夹中读取图像。
因此, html 和图像(资源)需要在同一个文件夹中。
无效的代码:
webView.loadHTMLString(html, baseURL: URL(fileURLWithPath: Bundle.main.bundlePath))
//html is a string.
有效的代码:
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
let filename = documentsDirectory.appendingPathComponent("index.html")
do {
//html is a string
try html.write(to: filename, atomically: true, encoding: String.Encoding.utf8)
} catch {
//...
}
webView.loadFileURL(filename, allowingReadAccessTo: documentsDirectory)
好的,首先你提到的路径
/var/mobile/Containers/Data/Application/31912F79-EB94-4DB1-84B8-68C7368B9160/Documents/t123t.jpg
重新打开应用程序后,带有随机字符串的文件夹(内部应用程序)总是会发生变化。
苹果出于安全目的实施了这一点。
let documentDirectory = FileManager.SearchPathDirectory.documentDirectory
let userDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(documentDirectory, userDomainMask, true).first
let path: String = paths!
//path has address of document directory and we need address of tmp directory where pictures are stored
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("\(url)")
let image = UIImage(contentsOfFile: imageURL.path)
当我遇到同样的问题时,这在我的第一个项目中对我有用。
希望我能帮到你 :)
快乐编码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.