1. 程式人生 > >iOS UIWebView的基本用法

iOS UIWebView的基本用法

    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];
    }