iOS UIWebView 使用大全

一、UIWebView的基礎使用

- (void)viewDidLoad {
    [super viewDidLoad];
    //    1、創建UIWebView:
    
    CGRect bouds = [UIScreen mainScreen].bounds;
    UIWebView* webView = [[UIWebView alloc]initWithFrame:bouds];
    
    //    2、加載在線資源http內容
    
    NSURL* url = [NSURL URLWithString:@"http://www.baidu.com"];//創建URL
    NSURLRequest* request = [NSURLRequest requestWithURL:url];//創建
    [webView loadRequest:request];//加載
    
    //    2、 加載本地文件的方法:
    
    /**
     *
     //第一種方法:
     
     NSString* path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];//mobile是根目錄,name是文件名稱,html是文件類型
     [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]]; //加載本地文件
     
     
     //第二種方法:
     
     NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
     
     NSString *filePath = [resourcePath stringByAppendingPathComponent:@"mobile.html"];
     
     NSString *htmlstring=[[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
     
     [webView loadHTMLString:htmlstring baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];

     */
    
    //    3、導航
    
    //    UIWebView類內部會管理瀏覽器的導航動作,通過goForward和goBack方法你可以控制前進與后退動作:
    
    [webView goBack];
    [webView goForward];

    //    4、UIWebViewDelegate委托代理

    webView.delegate = self;
    
    //    5、顯示網頁視圖UIWebView:
    
    [self.view addSubview:webView];
}

# pragma mark - UIWebView 的代理方法
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;//當網頁視圖被指示載入內容而得到通知。應當返回YES,這樣會進行加載
- (void)webViewDidStartLoad:(UIWebView *)webView { //當網頁視圖已經開始加載一個請求后,得到通知。
    //    [webView stopLoading];//取消載入內容
}
- (void)webViewDidFinishLoad:(UIWebView *)webView;//當網頁視圖結束加載一個請求之后,得到通知。
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error {
    //    [webView reload];//重載
}//當在請求加載中發生錯誤時,得到通知。會提供一個NSSError對象,以標識所發生錯誤類型。

以上是IOS中UIWebView的基礎使用要點詳解,接下來一些UIWebView的常用注意點。

二、IOS中UIWebView常用注意點:

1、與UIWebView進行交互,調用web頁面中的需要傳參的函數時,參數需要帶單引號,或者雙引號(雙引號要進行轉義在轉義字符前加\),傳遞json字符串時不需要加單引號或雙引號:

-(void)webViewDidFinishLoad:(UIWebView *)webView

{
    NSString *sendJsStr=[NSString stringWithFormat:@"openFile(\"%@\")", jsDocPathStr];
    [webView stringByEvaluatingJavaScriptFromString:sendJsStr];
    
}

2、在該代理方法中判斷與webView的交互,可通過html里定義的協議實現:

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType;

3、只有在webView加載完畢之后在能夠調用對應頁面中的js方法。(對應方法如第1條).

4、為webView添加背景圖片:

approvalWebView.backgroundColor=[UIColor clearColor];

//這句話很重要,webView是否是不透明的,no為透明 在webView下添加個imageView展示圖片就可以了
approvalWebView.opaque=NO;

5、獲取webView頁面內容信息:

NSString *docStr=[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.textContent"];//獲取web頁面內容信息,此處獲取的是個son字符串

SBJsonParser *parserJson=[[[SBJsonParser alloc]init]autorelease];

NSDictionary *contentDic=[parserJson objectWithString:docStr];//將json字符串轉化為字典

6、將文件下載到本地址然后再用webView打開:

    NSString *path = [[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"];
    NSString *resourceDocPath = [[NSString alloc] initWithString:path];
    
    self.filePath = [resourceDocPath stringByAppendingPathComponent:[NSString stringWithFormat:@"maydoc%@",docType]];
    
    NSData *attachmentData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:theUrl]];
    [attachmentData writeToFile:filePath atomically:YES];
    
    NSURL *url = [NSURL fileURLWithPath:filePath];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    
    [attachmentWebView loadRequest:requestObj];
    //刪除指定目錄下的文件
    
    NSFileManager *magngerDoc=[NSFileManager defaultManager];
    
    [magngerDoc removeItemAtPath:filePath error:nil];

8、處理webView展示txt文檔亂碼問題:

if ([theType isEqualToString:@".txt"]) {
    
    //txt分帶編碼和不帶編碼兩種,帶編碼的如UTF-8格式txt,不帶編碼的如ANSI格式txt
    
    //不帶的,可以依次嘗試GBK和GB18030編碼
    
    NSString* aStr = [[NSString alloc] initWithData:attachmentData encoding:NSUTF8StringEncoding];
    if (!aStr)
    {
        
        //用GBK進行編碼
        aStr=[[NSString alloc] initWithData:attachmentData encoding:0x80000632];
        
    }
    
    if (!aStr)
    {
        
        //用GBK編碼不行,再用GB18030編碼
        aStr=[[NSString alloc] initWithData:attachmentData encoding:0x80000631];
        
    }
    
    //通過html語言進行排版
    
    NSString* responseStr = [NSString stringWithFormat:
                             @"%@",aStr];
    [attachmentWebView loadHTMLString:responseStr baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
    
    return;
}

9、使用webView加載本地或網絡文件整個流程:

9.1、Loading a local PDF file into the web view

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    //從本地加載
    
    NSString *thePath = [[NSBundle mainBundle] pathForResource:@"iPhone_User_Guide" ofType:@"pdf"];
    
    if (thePath) {
        
        NSData *pdfData = [NSData dataWithContentsOfFile:thePath];
        
        [(UIWebView *)self.view loadData:pdfData MIMEType:@"application/pdf"
         
                        textEncodingName:@"utf-8" baseURL:nil];
        
    }
    //從網絡加載
    
    [self.myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"]]];
    
}

9.2、The web-view delegate managing network loading


- (void)webViewDidStartLoad:(UIWebView *)webView

{
    
    // starting the load, show the activity indicator in the status bar
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
}

- (void)webViewDidFinishLoad:(UIWebView *)webView

{
    
    // finished loading, hide the activity indicator in the status bar
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error

{
    
    // load error, hide the activity indicator in the status bar
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    
    // report the error inside the webview
    
    NSString* errorString = [NSString stringWithFormat:@"An error occurred:%@",error.localizedDescription];
    [self.myWebView loadHTMLString:errorString baseURL:nil];
    
}

9.3、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;
    
}

10、查找webView中的scrollview:

- (void) addScrollViewListener {
    
    UIScrollView* currentScrollView;
    
    for (UIView* subView in self.webView.subviews) {
        
        if ([subView isKindOfClass:[UIScrollView class]]) {
            
            currentScrollView = (UIScrollView*)subView;
            
            currentScrollView.delegate = self;
            
        }
        
    }

11、去掉webView的陰影,做成類似scrollView:

- (void)clearBackgroundWithColor:(UIColor*)color {
    // 去掉webview的陰影
    self.backgroundColor = color;
    for (UIView* subView in [self subviews])    
    {
        if ([subView isKindOfClass:[UIScrollView class]]) {
            for (UIView* shadowView in [subView subviews])  
            {
                if ([shadowView isKindOfClass:[UIImageView class]]) {
                    [shadowView setHidden:YES];   
                }   
            }   
        }   
    }
}

12、取消長按webView上的鏈接彈出actionSheet的問題:

-(void)webViewDidFinishLoad:(UIWebView *)webView {
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout = 'none';"];
}

13、取消webView上的超級鏈接加載問題:

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if (navigationType==UIWebViewNavigationTypeLinkClicked) {
        return NO;
    } else {
        return YES;
    }
}

14、在使用webView進行新浪微博分享時,webView會自動保存登陸的cookie導致項目中的分享模塊有些問題,刪除 webView的cookie的方法:

-(void)deleteCookieForDominPathStr:(NSString *)thePath

{
    //刪除本地cookie,thePath為cookie路徑通過打印cookie可知道其路徑
    
    for(NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
        
        if([[cookie domain] isEqualToString:thePath]) {
            
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
            
        }
        
    }
    
}

15、在UIWebView中使用flashScrollIndicators

使用UIScrollView時,我們可以使用flashScrollIndicators方法顯示滾動標識然后消失,告知用戶此頁面可以滾動,后面還有更多內容。UIWebView內部依賴于UIScrollView,但是其沒有flashScrollIndicators方法,但可以通過其他途徑使用此方法,如下所示。

 for (id subView in [webView subviews]){
        
        if ([subView respondsToSelector:@selector(flashScrollIndicators)]){
            [subView flashScrollIndicators];   
        }
    }

上述代碼片段可以到webViewDidFinishLoad回調中使用,加載完網頁內容后flash顯示滾動標識。
16、根據內容獲取UIWebView的高度:

有時候需要根據不同的內容調整UIWebView的高度,以使UIWebView剛好裝下所有內容,不用拖動,后面也不會留白。有兩種方式可根據加載內容獲取UIWebView的合適高度,但都需要在網頁內容加載完成后才可以,即需要在webViewDidFinishLoad回調中使用

①.使用sizeThatFits方法。


- (void)webViewDidFinishLoad:(UIWebView *)webView

{
    
    CGRect frame = webView.frame;
    
    frame.size.height = 1;
    
    webView.frame = frame;
    
    CGSize fittingSize = [webView sizeThatFits:CGSizeZero];
    
    frame.size = fittingSize;
    
    webView.frame = frame;
    
}

sizeThatFits方法有個問題,如果當前UIView的大小比剛好合適的大小還大,則返回當前的大小,不會返回最合適的大小值,所以使用sizeThatFits前,先將UIWebView的高度設為最小,即1,然后再使用sizeThatFits就會返回剛好合適的大小。

②、使用JavaScript

- (void)webViewDidFinishLoad:(UIWebView *)webView

{   
   CGRect frame = webView.frame;
    
    NSString *fitHeight = [webview stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"];
    
    frame.size.height = [fitHeight floatValue];
    
    webView.frame = frame;
}

總結:

首先 對IOS開發中的UIWebView控件的基本使用進行初步的詳解,提到了創建、設置屬性、設置背景、怎么樣加載網頁內容等一系列的基礎點,然后闡述使用UIWebView控件時常用用注意點,經常需要用到的地方,需要注意的地方,使得對開發ios APP混合模式的橋梁---UIWebView控件更加的了解、熟悉。UIWebView既能夠加載服務器提供的URI,又能夠加載本地的資源文件,還能夠加載服務器返回的網頁界面代碼,可想而知UIWebView是多么強大的一控件橋梁,以后在開發中使用到的地方會越來越多。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • IOS之UIWebView的使用 剛接觸IOS開發1年多,現在對于 混合式 移動端開發越來越流行,因為開發成本上、...
    學無止境666閱讀 45,907評論 5 53
  • OS之UIWebView的使用 剛接觸IOS開發1年多,現在對于 混合式 移動端開發越來越流行,因為開發成本上、速...
    知之未道閱讀 1,668評論 0 4
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,353評論 25 708
  • 今天相當不爽~~ 早起時不穿襪子,磨蹭著不肯洗臉刷牙,吃飯是吃幾口就完,飯后拿出她爸買的零食來吃。我真是沒耐心了,...
    圈_圈_閱讀 159評論 0 0
  • 我們可以ECMAScript的對象想象成散列表:無非就是一組名值對,其中值是數據或函數。 每個對象都是基于一個引用...
    dudu_du閱讀 119評論 0 0