一. WebView的基础用法
- 创建WebView:
self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(15, contentHeaderHeight - 0, SCREEN_WIDTH - 30, 1)];
self.webView.delegate = self;
NSString *url = @“”xxxxxxxxxxxxxxx”;
[self.webView loadRequest:self.requestrequest];
[self.headerBottomView addSubview:self.webView];
- WebView的代理方法:
- (void)webViewDidStartLoad:(UIWebView *)webView; //WebView内容即将开始加载
- (void)webViewDidFinishLoad:(UIWebView *)webView; //WebView内容加载完成
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error; //WebView内容加载错误
二. 获取WebView内容高度
方法1. 通过WebView的代理方法获取内容高度
优点:所有内容一次加载完成,直接获取内容的全部高度
缺点:当内容较多时,加载速度偏慢,白屏等待时间较长,用户体验差
代码:
//webview内容已加载完毕的方法
- (void)webViewDidFinishLoad:(UIWebView *)webView{
//获取webview的高度
float height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
//刷新WebView的高度
}
方法2. 通过KVO获取WebView内容高度
优点:不会出现长时间白屏等待,文字先加载出来,然后才加载图片。
缺点:不能够一次性获取内容的全部高度,图片会一点点加载出来,等待全部加载完成才可以滑动整个WebView。
代码:
//首先在WebView初始化的时候给WebView添加观察对象
[self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
//然后实现KVO的方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
//获取webview的高度
if ([keyPath isEqualToString:@"contentSize"]) {
float height = [[_webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
}
}
//dealloc中移除观察者对象
[self.webView.scrollView removeObserver:self forKeyPath:@"contentSize"];
三. 获取WebView的Cookie
- 配置WebView
UIWebView *webview = [[UIWebView alloc]initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height-20)];
NSURL *url = [NSURL URLWithString:@”xxxxxxxxxxxxxxx”];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webview loadRequest:request];
[self.view addSubview:webview];
- 拿到WebView页面的Cookie
NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray *cookies = [sharedHTTPCookieStorage cookiesForURL:[NSURL URLWithString:@”xxxxxxxxxxxxxxx”];
NSEnumerator *enumerator = [cookies objectEnumerator];
for (NSHTTPCookie *cookie in enumerator)
{
if ([[cookie name] isEqualToString:@"PHPSESSID"])
{
[UserManager shraeUserManager].user.PHPSESSID = [cookie value];
}
}
- 删除WebView页面的Cookie
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray *tmpArray = [NSArray arrayWithArray:[cookieJar cookies]];
for (id obj in tmpArray)
{
[cookieJar deleteCookie:obj];
}
四. WebView和JS进行交互
- 需要前端和后端约束好交互条件
// js调用前端方法(点击js中的图片获取图片URL和相关信息)
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
// ForunIos就是和后台约束好的字段
context[@"ForumIos"] = ^() {
// args里面就是js返回给前台的信息
NSArray *args = [JSContext currentArguments];
[ ForumNotificationCenter postNotificationName:@"browseImageNotificationName" object:[NSString stringWithFormat:@"%@",args[1]]];
};