简体   繁体   中英

Can not load images from `Documents` directory on device

On simulator this works. Here is the path I printed while saving an image:
/var/mobile/Containers/Data/Application/31912F79-EB94-4DB1-84B8-68C7368B9160/Documents/t123t.jpg

And this is img tag in html which should load image into webView(worked fine on simulator):
img src="file:///var/mobile/Containers/Data/Application/31912F79-EB94-4DB1-84B8-68C7368B9160/Documents/t123t.jpg">

As I can see everything looks ok here, I thought problem should be in the path, I removed part file:// from img src but it didnt help me.

Solved
For some reason, images in Documents weren't accessible this way with loading html from string. I needed to create a html file in Documents folder to be able to read images from that folder.
So, html and images(resources) need to be in the same folder .
Code that didn't work:

webView.loadHTMLString(html, baseURL: URL(fileURLWithPath: Bundle.main.bundlePath))
//html is a string.

Code that works:

 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)

Okay firstly the path you mentioned

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

Folder with random string (Inside Application) always changes after reopening the app.

Apple implemented this for security purpose.

            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)

This worked for me in my first project when I got stuck in same problem.

Hope I helped you :)

Happy Coding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM