IOS網絡第七天WebView-03js中調用webView中的代碼

***********html

#import "HMViewController.h"

@interface HMViewController () <UIWebViewDelegate>
@end

@implementation HMViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // 1.webView
    UIWebView *webView = [[UIWebView alloc] init];
    webView.frame = self.view.bounds;
    webView.delegate = self;
    [self.view addSubview:webView];
    
    // 2.加載網頁
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
}

#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView
{

}

/**
 *  webView每當發送一個請求以前,都會先調用這個方法(能攔截全部請求)
 */
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *url = request.URL.absoluteString;
    NSRange range = [url rangeOfString:@"hm://"];
    NSUInteger loc = range.location;  //位置
    if (loc != NSNotFound) { // url的協議頭是hm
        // 方法名
        NSString *method = [url substringFromIndex:loc + range.length];
        
        // 轉成SEL
        SEL sel = NSSelectorFromString(method);// method = 「call」 或 」openCamera「
        [self performSelector:sel withObject:nil];
    }
    return YES;
}

/**
 *  打電話
 */
- (void)call
{
    NSLog(@"call----");
}

/**
 *  打開照相機
 */
- (void)openCamera
{
    NSLog(@"openCamera----");
}

@end
相關文章
相關標籤/搜索