iOS WKWebview使用loadHTMLString(_ baseURL:)方法无法加载图像和读取CSS。

3

我知道这个问题以前已经被问过了,但我的情况有一点不同。

我试图在WKWebview上调用loadHTMLString(_ baseURL:),而我的基础URL位于AppData/Documents目录中。

我需要加载HTMLstring并且它需要使用该目录中的图像。 HTMLstring没有任何位置,我下载字符串进行解析、修改和加载。

据我所知,由于某些安全问题,我不能这样做(在UIWebview上运行良好),因此HTMLstring被加载但是图像和CSS却没有被加载。

另外,我不能调用loadFileURL(_, allowingReadAccessTo:),因为我没有文件而是一个HTMLstring,也无法在调用之前将其保存到文件中,因为存在自己的安全问题。

我的代码很庞大,而且非常复杂,我希望以最轻松的方式实现加载图像。

有人有想法吗?


1
ozd,你找到解决方案了吗?我一直无法使用loadHTMLString从文档目录中获取本地图像进行显示。(在模拟器上可以工作,但在设备上不行。)一个解决方法可能是将图像数据进行base64编码并添加到html中,但在某些情况下这并不是一个好的解决方案(例如,我仍然需要让本地视频工作)。 - Ernie Thomason
2个回答

2

我希望我能给出更好的答案,如果有人有更好的答案,我会非常乐意接受。最终我把我的文件移动到了临时目录 :( 我使用了这个 -

extension FileManager
{
    func copyToTemporaryDirectory(itemIn itemURL: URL) -> URL?
    {
        let tempDirectoryURL    = URL(fileURLWithPath: NSTemporaryDirectory())
        let fileName            = itemURL.lastPathComponent
        let copyURL             = tempDirectoryURL.appendingPathComponent(fileName)
        let fileManager         = FileManager.default

        do {

            if fileManager.fileExists(atPath: copyURL.path)
            {
                try fileManager.removeItem(at: copyURL)
            }

            try FileManager.default.copyItem(at: itemURL, to: copyURL)

            return copyURL

        }
        catch let error
        {
            logger.debug("copyItem error: \(error.localizedDescription)")
            return nil
        }
    }
}

然后使用loadHtmlString和指向该目录的URL。从该目录,WKWebview可以获取所有内容。


你有用HTML字符串创建一个文件吗? - Skywalker

2
我不确定您放置源HTML代码的位置。我假设您将其放置在Bundle中。这是我的想法。
在图像标签的HTML文件中,我们应该按照此模板进行操作。
<image src="{xxx}" ....>

然后在iOS代码中,我们将通过图片路径来替换src,并加载到WKWebview中:

// make sure you have the image name and extension (for demo purposes, I'm using "myImage" and "png" for the file "myImage.png", which may or may not be localized)
NSString *imageFileName = @"myImage";
NSString *imageFileExtension = @"png";

// load the path of the image in the main bundle (this gets the full local path to the image you need, including if it is localized and if you have a @2x version)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageFileName, imageFileExtension]];

// generate the html tag for the image (don't forget to use file:// for local paths)
NSString *imgFilePath = [NSString stringWithFormat:@"file://%@", imagePath];

// Replace an imagepath
NSString *path = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"html"];
NSString *html = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
html = [html stringByReplacingOccurrencesOfString:@"{xxx}" withString:imgFilePath];


// Folder html url
NSString *destinationHTMLFolder = [[NSBundle mainBundle] pathForResource:@"myhtml" ofType:@""];
NSURL *destination = [NSURL fileWithPath: destinationHTMLFolder]

[self.webView loadHTMLString:html baseURL:destination];  

注意:请确保baseURL指向HTML文件夹。在将HTML源代码添加到Xcode时,应该选择“创建文件夹引用”选项。

我不确定...它能处理多张图片吗?另外,为什么会有效?难道不是阻止它首先读取文件的问题也会阻止图像加载吗?此外,我需要使用该目录中的CSS文件...你知道它是否也适用于CSS吗? - ozd
喜欢编程概念。您还可以在CSS文件中更改图像路径。 - Duc Nguyen
1
你测试过使用WKWebView并且在Document文件夹中有源文件吗?因为这个方法对我不起作用。同时,我从服务器动态地获取HTML并且它是加密的,所以我下载文件、获取内容、将其转换为HTML格式,最终才将HTML加载到我的webView上。因此,我没有任何HTML文件被保存在任何地方。 - ozd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接