iOS UIWebView的基本用法

来源:互联网 发布:ios Linux 编辑:程序博客网 时间:2024/04/29 00:48
    UIWebView *webView = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];    webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]]];    [self.view addSubview:webView];

报错:NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802) 或者 App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

其中在iOS 9 新建的项目中这种加载 要注意plist的配置 App Transport Security Settings 中添加Allow Arbitrary Loads 改 NO 为 YES。

加载本地HTML

    // 加载本地文件    //1    NSString* path = [[NSBundle mainBundle] pathForResource:@"name" ofType:@"html" inDirectory:@"library"];//library是根目录,name是文件名称,html是文件类型    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]];    //2    NSString * filePath = [[NSBundle mainBundle] pathForResource:@"agreement" ofType:@"html"];    NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];    [webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:filePath]];    //3    NSString *resourcePath = [[NSBundle mainBundle] resourcePath];    NSString *filePath = [resourcePath stringByAppendingPathComponent:@"name.html"];    NSString *htmlstring=[[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];    [webView loadHTMLString:htmlstring baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];

一些属性的设置:

 webView.scalespageToFit = YES; // 对页面进行缩放以适应屏幕

 webView.detectsPhoneNumbers = YES; //检测网页上的电话号码,单击可以拨打

//为UIWebview添加背景图片

webView.backgroundColor=[UIColor clearColor];

webView.opaque=NO;//这句话很重要,webView是否是不透明的,no为透明 在webView下添加个imageView展示图片就可以了

    [webView goBack];      //后退    [webView goForward];   //前进    [webView reload];      //重载    [webView stopLoading]; //取消载入内容

一些代理方法:

#pragma mark ---Delegate-(void) webViewDidStartLoad:(UIWebView *)webView{        NSLog(@"开始加载---") ;<pre name="code" class="objc">   // starting the load, show the activity indicator in the status bar       [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;}- (void) webViewDidFinishLoad:(UIWebView *)webView {    NSLog(@"加载完成---");   // finished loading, hide the activity indicator in the status bar   [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;   //获取当前页面的title           NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];       NSLog(@"title====%@",title);           //获取当前URL           NSString *URL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];       NSLog(@"URL===%@",URL);           //得到网页代码           NSString *html = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.innerHTML" ];        NSLog(@"html====%@",html);// document.documentElement.textContent           //拼接字符串 根据网页name找到控价并赋值           NSString *str = @"随_的简书";       NSString *JSStr = [NSString stringWithFormat: @"document.getElementsByName('q')[0].value = ('%@');",str];       [webView stringByEvaluatingJavaScriptFromString:JSStr];}- (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {    NSLog(@"加载失败===%@",error);   // report the error inside the webview   NSString* errorString = [NSString stringWithFormat:@"An error occurred:%@",error.localizedDescription];   [self.myWebView loadHTMLString:errorString baseURL:nil];}

其中:-(BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*) reuqest navigationType: (UIWebViewNavigationType)navigationType;//当网页视图被指示载入内容而得到通知。应当返回YES,这样会进行加载。通过导航类型参数可以得到请求发起的原因,可以是以下任意值:

UIWebViewNavigationTypeLinkClicked

UIWebViewNavigationTypeFormSubmitted

UIWebViewNavigationTypeBackForward

UIWebViewNavigationTypeReload

UIWebViewNavigationTypeFormResubmitted

UIWebViewNavigationTypeOther


scrollview的代理方法

//当网页位置为顶部 不允许继续下拉- (void) scrollViewDidScroll:(UIScrollView *)scrollView {        if (self.webView.frame.origin.y == 0) {                self.webView.scrollView.bounces = NO;                return;    }}


UIWebView的小知识点最下面的知识点

1. 

//Stopping a load request when the web view is to disappear- (void)viewWillDisappear:(BOOL)animated{   if ( [self.myWebView loading] ) {       [self.myWebView stopLoading];   }   self.myWebView.delegate = nil; // disconnect the delegate as the webview is hidden   [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;}

 2.加载txt文件中文显示乱码问题

    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, UIScreenHeigth + 64)];    webView.scalesPageToFit = YES;    [self.view addSubview: webView];    //将带有中文的URL进行UTF8编码    NSString *urlString = [self.attachUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    ///编码可以解决中文显示乱码问题    NSStringEncoding *useEncodeing = nil;    //带编码头的如utf-8等,这里会识别出来    NSString *body = [NSString stringWithContentsOfURL:[NSURL URLWithString:self.attachUrl] usedEncoding:useEncodeing error:nil];    if ([_attachType isEqualToString:@"text/plain"] || [_attachType isEqualToString:@"application/msword"]) {        //识别不到,按GBK编码再解码一次.这里不能先按GB18030解码,否则会出现整个文档无换行bug。        if (!body) {            body = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:0x80000632 error:nil];        }        //还是识别不到,按GB18030编码再解码一次.        if (!body) {            body = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:0x80000631 error:nil];        }        //展现        if (body) {            [webView loadHTMLString:body baseURL: nil];        }    }    else {        NSURL *requestUrl = [NSURL URLWithString:urlString];        NSURLRequest *request = [NSURLRequest requestWithURL:requestUrl];        [webView loadRequest:request];    }


0 0
原创粉丝点击