2
votes

I have an app with downloaded images to be displayed in local html. I am still using Objective-C because this app is 4 years old. When first launch the app, it will download the images and other dynamic content (which I check, it is in Documents/content/ directory).

I have this code to get the content location:

NSString *contentBasePath = [app.contentManager contentBasePath];

which I get:

/var/mobile/Containers/Data/Application/4AFD30E2-F4F7-405A-9FE9-1857EEC11CC7/Documents/content

Then I have a few html pages that will call the downloaded images dynamically:

<div class="box-round benefits-thumbnail" style="background-image:url('file://{{../contentBasePath}}/{{filename}}');"></div>

Which I check, {{../contentBasePath}} will get:

/var/mobile/Containers/Data/Application/4AFD30E2-F4F7-405A-9FE9-1857EEC11CC7/Documents/content

and {{filename}} will get

example.jpg

which is all correct.

All this works with uiwebview. However I need to use wkwebview, the image did not show up.

I tried:

<div class="box-round benefits-thumbnail" style="background-image:url('{{../contentBasePath}}/{{filename}}');"></div>

and it still not working.

I googled and read around and it seems like wkwebview do not allow absolute path. so I tried as per this suggest:

[_webConfig.preferences  setValue:@YES forKey:@"allowFileAccessFromFileURLs"];

and still not working.

How can I resolve this?

2
did you find any work around ?? I have a similar issue in swift , images come in simulator but not in real device. - iMinion

2 Answers

1
votes

Seems like this is a limitation of the WebKit. As a workaround, you can write the HTML contents into a file in the documents directory and load it using [webView loadFileURL:fileUrl allowingReadAccessToURL:dirUrl]

Link to docs: https://developer.apple.com/documentation/webkit/wkwebview/1414973-loadfileurl

0
votes

The files must be in the document directory.

I implemented the following to retrieve a document:

    let documentDirUrl = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
    let fileNameWithExtension = "IMG_0002.PNG"
    let indexFileUrl = documentDirUrl.appendingPathComponent(fileNameWithExtension)
    if FileManager.default.fileExists(atPath: indexFileUrl.path) {
        webView.loadFileURL(indexFileUrl, allowingReadAccessTo: documentDirUrl)
    }