我知道这个问题以前曾被问过,但我的情况有些不同。
我正在尝试打电话给loadHTMLString(_ baseURL:)
on WKWebview
我的 baseURL 位于AppData/Documents
目录。
我需要HTMLstring
加载并且需要使用该目录中的图像。这HTMLstring
不在任何地方,我下载字符串解析它,修改它并加载它。
据我了解,由于某种安全问题,我无法这样做(它在 UIWebview 上效果很好),所以HTMLstring
已加载,但图像和CSS
不是。
另外,我也不能打电话loadFileURL(_, allowingReadAccessTo:)
因为我没有文件 我有一个HTMLstring
由于我自己的安全问题,无法在通话之前将其保存到文件中。
我的代码很大并且很复杂,我希望以最轻松的方式实现加载图像。
有人有想法吗?
我不确定你把它放在哪里的源 HTML 代码。我假设您将其放入捆绑包中。这是我的想法。
在图像标签的 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 时,应该有一个“创建文件夹引用”选项。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)