zoukankan      html  css  js  c++  java
  • 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);
            
    }];
  • 相关阅读:
    git操作详解
    藏医诊疗管理系统
    广告的转化率预估
    python字符串及其内置函数详解
    python数据类型和运算符及运算符的优先级
    lunix常用命令
    返回结果的HTTP状态码
    简单的http协议
    git 上传项目到分支
    安装及使用webpack
  • 原文地址:https://www.cnblogs.com/dhui69/p/5596917.html
Copyright © 2011-2022 走看看