iOS WebView 加载本地资源(图片,文件等)

NSString *path = [[NSBundle mainBundle] pathForResource:@"关于.docx" ofType:nil];  
    NSURL *url = [NSURL fileURLWithPath:path];  
    NSLog(@"%@", [self mimeType:url]);  
      
      
    //webview加载本地文件,可以使用加载数据的方式  
    //第一个诶参数是一个NSData, 本地文件对应的数据  
    //第二个参数是MIMEType  
    //第三个参数是编码格式  
    //相对地址,一般加载本地文件不使用,可以在指定的baseURL中查找相关文件。  
      
    //以二进制数据的形式加载沙箱中的文件,  
    NSData *data = [NSData dataWithContentsOfFile:path];  
      
    [self.webView loadData:data MIMEType:@"application/vnd.openxmlformats-officedocument.wordprocessingml.document" textEncodingName:@"UTF-8" baseURL:nil];  
NSString *html;
    
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSString *htmlFilePath=[cachePath stringByAppendingPathComponent:@"123.html"];
    //    NSString *html=[[NSString alloc]initWithContentsOfFile:htmlFilePath encoding:NSUTF8StringEncoding error:nil];
    NSURL *baseURL= [NSURL fileURLWithPath:htmlFilePath];
    if ([[NSFileManager defaultManager] fileExistsAtPath:htmlFilePath]) {
        NSString *string = [NSString stringWithContentsOfFile:htmlFilePath
                                                     encoding:NSUTF8StringEncoding
                                                        error:nil];
        
        if (string) {
            html = string;
        }
    }
//    NSString *path = [[NSBundle mainBundle] bundlePath];
//    NSURL *baseURL2 = [NSURL fileURLWithPath:path];
    [self.webView loadHTMLString:html baseURL:baseURL];

至于在沙盒里面的图片,想加载到web里面,发现在模拟器里面是正常,然后再真机上加载不出来

参考这篇文章 iOS Native加载H5中的图片  github  源码:https://github.com/CoderJackyHuang/iOSLoadWebViewImage

多次尝试,无果,找资料时发现下面的方法可以加载沙盒中图片

NSData *imageData=[NSData dataWithContentsOfFile:imagePath];//imagePath :沙盒图片路径
NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[imageData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]];
NSString *strJs=[NSString stringWithFormat:@"document.images[0].src='%@'",imageSource];
[webView evaluateJavaScript:strJs completionHandler:^(id _Nullable response, NSError * _Nullable error) {
   NSLog(@"webView response: %@ error: %@", response, error);
        
}];

 

posted on 2016-06-18 21:31  二狗你变了  阅读(18571)  评论(2编辑  收藏  举报

导航