UIWebView

  • 加载请求
  • JS和OC互相调用
  • 利用NSInvocation 和 performSelector 实现传递无限参数
  • 异常捕捉
    • NSException
    • 崩溃统计(友盟)
//加载网页
[self.webView loadRequest:[NSURLRequest requestWithURL:[[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"]]];

#pragma mark - 
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//    [webView stringByEvaluatingJavaScriptFromString:@"alert(100);"];
    
    // 利用JS获得当前网页的标题
//    self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title;"];
    
//    NSString *result = [webView stringByEvaluatingJavaScriptFromString:@"login();"];
//    NSLog(@"%@", result);
}

/**
 * 通过这个方法完成JS调用OC
 * JS和OC交互的第三方框架:WebViewJavaScriptBridge
 */
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *url = request.URL.absoluteString;
    NSString *scheme = @"http://";
    if ([url hasPrefix:scheme]) {
        
        NSString *methodName = [url substringFromIndex:scheme.length];
        [self performSelector:NSSelectorFromString(methodName) withObject:nil];
        
        return NO;
    }
    
    NSLog(@"想加载其他请求,不是想调用OC的方法");
    
    return YES;
}

//js调用OC代码带参数
- (void)sendMessage
{
// url == http://sendMessage_?200
    NSString *url = request.URL.absoluteString;
    NSString *scheme = @"xmg://";
    if ([url hasPrefix:scheme]) {
        // 获得协议后面的路径  path == sendMessage_number2_?200&300
        NSString *path = [url substringFromIndex:scheme.length];
        // 利用?切割路径
        NSArray *subpaths = [path componentsSeparatedByString:@"?"];
        // 方法名 methodName == sendMessage:number2:
        NSString *methodName = [[subpaths firstObject] stringByReplacingOccurrencesOfString:@"_" withString:@":"];
        // 参数  200&300
        NSArray *params = nil;
        if (subpaths.count == 2) {
            params = [[subpaths lastObject] componentsSeparatedByString:@"&"];
        }
        // 调用
        [self performSelector:NSSelectorFromString(methodName) withObjects:params];
        
        return NO;
    }

你可能感兴趣的:(UIWebView)