`

UIWebView使用技巧2以及UIWebviewDelegate使用

    博客分类:
  • ios
阅读更多

 

详细参考:

 

http://blog.csdn.net/cococoolwhj/article/details/7019828

 

http://blog.sina.com.cn/s/blog_68501a5e010110hr.html

 

webView加载内容有三个方法:

– loadData:MIMEType:textEncodingName:baseURL:

这个方法没有使用过

– loadHTMLString:baseURL:

 

– loadRequest:

通过request加载一个page,只能加载整个html文件。代码:

 

 UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
    NSURL *url =[NSURL URLWithString:URL_LOGIN];
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    [webView loadRequest:request];

 

 

 

 

UIWebViewDelegate 

 

– webView:shouldStartLoadWithRequest:navigationType:( 将要请求,还未请求)

这里会有三个参数:webview 当前的webview,可以通过webview的URL获取当前现实的网址

request 将要发起的request请求,即使是在ajax中打开新页面也会调用该方法

navigationType开始加载request时,用户的行为

– webViewDidStartLoad: (请求已经开始)

发送一个reeust请求时调用哪个(在ajax中请求不调用该方法)

– webViewDidFinishLoad:(请求结束)

当一个请求结束时调用该方法(在ajax中请求不调用该方法)

– webView:didFailLoadWithError:

请求失败时调用该方法(在ajax中请求不调用该方法)

 

设置UIWebView的user agent

    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"GuoKr-IOS-1.5", @"UserAgent", nil];

    [[NSUserDefaultsstandardUserDefaults] registerDefaults:dictionary];

      user agent可以用来表示浏览器,不同版本的浏览器有不同的user agent。服务器可以根据不同的user agent做出不同的反应。例如区分移动浏览器和pc浏览器,显示不同内容。 

在代码中可以通过下面的代码获取当前控件的UA:

NSString *ua = [request valueForHTTPHeaderField:@"User-Agent"];

如果只是想修改某个reqeust的UA,可以在– webView:shouldStartLoadWithRequest:navigationType:中修改代码如下:

需要使用NSMutableRequest来修改reuqest

 

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:request.URL cachePolicy:request.cachePolicy timeoutInterval:request.timeoutInterval];
    
//    NSString *ua = [request valueForHTTPHeaderField:@"User-Agent"];
//    NSLog(@"%@",ua);
    
    NSString *temp = [NSString stringWithFormat:@"%@ GuoKr-IOS/1.5",[request valueForHTTPHeaderField:@"User-Agent"]];
    [mRequest setValue:temp forHTTPHeaderField:@"User-Agent"];
    request = mRequest;
    
//    NSString *ua1 = [request valueForHTTPHeaderField:@"User-Agent"];
//    NSLog(@"%@",ua1);
    
    return YES;
}

另一种方法:
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"Your user agent", @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
 参考:http://stackoverflow.com/questions/478387/change-user-agent-in-uiwebview-iphone-sdk

 

 

 

设置代理:http://www.oschina.net/question/54100_38005

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics