1、UIWebView加载网页:
接口:
- (void)loadRequest:(NSURLRequest *)request;
- (void)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;
- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL *)baseURL;
示例:
NSString *url = @"www.baidu.com";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setTimeoutInterval:30];
self.webView = [[UIWebView alloc] init];
self.webView.delegate = self;
[self.webView loadRequest:request];
关闭webView前需要将delegate置为nil,并停止加载网页资源以防crash:
_webView.delegate = nil;
[_webView stopLoading];
2、safari调试UIWebView网页:
mac safari-》Preferences(设置)-》advanced(高级)-》勾选开发模式
真机(模拟器)-》设置-》safari-》高级-》开启Web检查器和JavaScript
之后真机或者模拟器webView可以用safari进行调试:
3、Objective-C调用UIWebView js方法:
接口:
- (nullable NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;
在webiview页面加载完成之后调用stringByEvaluatingJavaScriptFromString:方法运行JS
示例:
[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('kw').value = 'UIWebview';document.getElementById('su').click();"];
注意:
stringByEvaluatingJavaScriptFromString:方法只有在webView网页加载结束后调用才会真正执行js代码。
如果判断webView页面是否加载完成,需要满足两个条件:
- webView delegate回调webViewDidFinishLoad:方法;
- webViewDidFinishLoad:方法回调后webView网页资源加载完成,用webView.isLoading来判断(可用其他方法)。
- (void)webViewDidFinishLoad:(UIWebView *)webView {
//网页为www.baidu.com
if ([self isTargetUrl:webView.request.URL.absoluteString] && !webView.isLoading) {
NSString *js = @"document.getElementById('kw').value = 'UIWebview';document.getElementById('su').click();";
[webView stringByEvaluatingJavaScriptFromString:js];
}
}