美文网首页
UIWebView加载网页

UIWebView加载网页

作者: zhouios | 来源:发表于2017-04-01 10:11 被阅读0次
     1,加载的是html字符串
     UIWebView *web = [[UIWebView alloc] initWithFrame:self.view.bounds];
    
    //为yes的时候,表示加载的网页可以缩放,为no的时候,网页不可以缩放,默认是no
    web.scalesPageToFit = YES;
    
     // 加载 html 字符串: baseURL:基准的地址:相对路径/绝对路径
     [web loadHTMLString:html baseURL:nil];
    
      // 将浏览器加载在view 上
     [self.view addSubview:web];
    
    2,加载的是网页地址(地址含有中文)
    NSString *urlString = @"http://127.0.0.1/服务器资料/1.html";
    // 在 url 中,不能出现汉字,只能是 ASCII 吗! 如果 url 中出现了 汉字等特殊符号,必须使用百分号转译!
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet letterCharacterSet]];
    NSURL *url = [NSURL URLWithString:urlString];
    // 可变的网络请求!
    // NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // cachePolicy: 网络缓存策略:枚举常量
    // timeoutInterval: 请求超时时间! 默认情况下,最大的请求超时时间是 1分钟! 在开发中,一般设 15S
     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:15];
    
    UIWebView *web = [[UIWebView alloc] initWithFrame:self.view.frame];
        
    [web loadRequest:request];
    [self.view addSubview:web];
    
    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
        
    // 可变的网络请求!
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 告诉服务器,客户端的软件环境
    // [request setValue:@"iPhone" forHTTPHeaderField:@"User-Agent"]; // 直接这样写,会出来一些简单的界面
    // User-Agent :通过改变这个量,可以得到自己想要的一些界面!
    // 通过设置这个值,可以欺骗服务器,给我们返回不同的数据!
    // 现在,一些大公司的页面都做成 响应式(自动适配PC 端 和 移动端) 的!
    [request setValue:@"iPhone AppleWebKit" forHTTPHeaderField:@"User-Agent"];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            //
            
            NSLog(@"response:%@",response);
            
            [data writeToFile:@"/Users/apple/Desktop/baidu.html" atomically:YES];
            
            UIWebView *web = [[UIWebView alloc] initWithFrame:self.view.frame];
            
            // 浏览器直接加载 二进制数据! MIMEType :文件类型 == "Content-Type" = "text/html;  textEncodingName :编码方式 baseURL:基准地址
            [web loadData:data MIMEType:nil textEncodingName:nil baseURL:url];
            
            [self.view addSubview:web];
            
        }];
    

    相关文章

      网友评论

          本文标题:UIWebView加载网页

          本文链接:https://www.haomeiwen.com/subject/zjfiottx.html