【问题标题】:Can not load images from `Documents` directory on device无法从设备上的“文档”目录加载图像
【发布时间】:2020-03-04 08:30:10
【问题描述】:

在模拟器上这有效。 这是我在保存图像时打印的路径:
/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://,但这对我没有帮助。

【问题讨论】:

标签: ios swift image webview ios12


【解决方案1】:

已解决
出于某种原因,Documents 中的图像无法通过从字符串加载 html 以这种方式访问​​。我需要在Documents 文件夹中创建一个html file 才能从该文件夹中读取图像。
所以,html 和 images(resources) 需要在同一个文件夹中
无效的代码:

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)

【讨论】:

    【解决方案2】:

    好的,首先你提到的路径

    /var/mobile/Containers/Data/Application/31912F79-EB94-4DB1-84B8-68C7368B9160/Documents/t123t.jpg
    

    带有随机字符串的文件夹(应用程序内部)在重新打开应用程序后总是会发生变化。

    Apple 出于安全目的实现了这一点。

                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)
    

    当我遇到同样的问题时,这对我的第一个项目很有用。

    希望我能帮到你:)

    快乐编码

    【讨论】:

    • 谢谢,但我看不出这对我有什么帮助。我所有的图像都应该下载到 Documents 文件夹中,然后应该从该文件夹中读取 img source(html) 并将图像加载到 webView 中。
    • 正如我之前所说,由于 Apple 的安全实施,Documents 目录的父文件夹总是在每次启动应用程序时发生变化,所以我的代码将搜索文档目录,无论它放在哪里。如果你想要 URL,那么 imgURL 会给你 URL,如果你想要图像本身,那么 image 变量就会有你的图像。
    猜你喜欢
    • 2012-01-27
    • 1970-01-01
    • 2010-11-04
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2013-08-27
    • 1970-01-01
    相关资源
    最近更新 更多