WKWebView不允许直接从文件存储(文档目录)访问文件,要从文档目录访问文件,您必须使用loadFileURL:allowingReadAccessToURL:
方法,以下是我的代码。
在ViewDidLoad中
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSURL *url = [[NSBundle mainBundle] URLForResource: @"fileupload" withExtension: @"html"];
NSData *data = [[NSData alloc] initWithContentsOfFile:[url path]];
[data writeToFile:[documentsPath stringByAppendingPathComponent:@"fileupload.html"] atomically:YES];
UIImage *image = [UIImage imageNamed:@"yoga.png"];
NSData *pngData = UIImagePNGRepresentation(image);
filePath = [documentsPath stringByAppendingPathComponent:@"yoga.png"];
[pngData writeToFile:filePath atomically:YES];
filePath = [self documentsPathForFileName:@"yoga.png"];
NSLog(@"File path: %@", [self documentsPathForFileName:@"yoga.png"]);
NSURL *fileurl = [NSURL fileURLWithPath:[documentsPath stringByAppendingPathComponent:@"fileupload.html"]];
[webView loadFileURL:fileurl allowingReadAccessToURL:[NSURL fileURLWithPath:documentsPath]];
以上代码将一个图像从bundle保存到文档目录,同时它还保存了一个HTML文件(该文件将使用img标签来加载图像)。
下面是didFinishNavigation:
//Sending Path to javascript
[webView evaluateJavaScript:[NSString stringWithFormat:@"upload('%@')", filePath] completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
NSLog(@"Java script called");
}];
获取文件 URL 的实用方法
- (NSString *)documentsPathForFileName:(NSString *)name
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSURL *url = [NSURL fileURLWithPath:[documentsPath stringByAppendingPathComponent:name]];
return [url absoluteString];
}
最后是包含从Webview获取路径和加载图像方法的HTML文件。
<html>
<head><title>demo</title>
<script>
function upload(path)
{
alert(path);
var img = document.createElement("IMG");
img.src = path;
img.border = 1;
img.height = 750;
img.width = 900;
document.getElementById('imageDiv').appendChild(img);
}
function convertURIToImageData(URI) {
return new Promise(function(resolve, reject) {
if (URI == null) return reject();
var canvas = document.createElement('canvas'),
context = canvas.getContext('2d'),
image = new Image();
image.addEventListener('load', function() {
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0, canvas.width, canvas.height);
resolve(context.getImageData(0, 0, canvas.width, canvas.height));
}, false);
image.src = URI;
});
}
</script>
</head>
<body>
<p><h1>This is a Demo !!!</h1></p>
<div id="imageDiv"></div>
</body>
</html>
上述方法是我找到的从文档目录加载图像/文件的唯一方法。
您还可以将图像/文件以数据URL的形式发送,并将其传递给javascript方法(已在html文件中编写),只需将图像转换为NSData并进行基本编码即可,javascript将自行将数据URL转换为图像对象。
UIImage转数据URL转换:
UIImage *img = [UIImage imageNamed:@"yoga.png"];
NSData *data = UIImageJPEGRepresentation(img, 0.90);
data = [data base64EncodedDataWithOptions:0];
NSString *dataurl = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
干杯!!!