iOS Hook WebView 的代理方法

最近在使用 DCloud 團(tuán)隊(duì)開發(fā)的 HTML5+ 來開發(fā) Hybrid 應(yīng)用。它們使用 iOS 系統(tǒng)原生 UIWebView 和 WKWebView 來加載資源。我們的應(yīng)用有個需求,就是在 webview 加載完頁面或者加載頁面之前加入一些東西。比如:加載完頁面后,根據(jù) HTML 的 title 標(biāo)簽來設(shè)置導(dǎo)航欄標(biāo)題。

原生想要插手頁面加載周期,只能靠代理方法。但是因?yàn)闆]法修改源碼,所以只能找其它辦法。主要思路是:使用 Method Swizzle 找出代理對象然后再換掉代理方法實(shí)現(xiàn)。

以 UIWebView 為例,具體操作如下:

第一步,通過交換 setDelegate 的實(shí)現(xiàn),找到目標(biāo)代理對象所屬的類;

UIWebView+Intercepter.m

- (void)p_setDelegate:(id<UIWebViewDelegate>)delegate
{
    [self p_setDelegate:delegate];
    Class delegateClass = [self.delegate class];
    // 進(jìn)一步交換 delegateClass 的代理方法
    [UIWebViewDelegateHook exchangeUIWebViewDelegateMethod:delegateClass];
}

#pragma mark - Method Swizzling
+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [super class];
        
        // When swizzling a class method, use the following:
        // Class class = object_getClass((id)self);
        
        SEL originalSelector = @selector(setDelegate:);
        SEL swizzledSelector = @selector(p_setDelegate:);
        
        Method originalMethod = class_getInstanceMethod(class, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
        
        BOOL didAddMethod =
        class_addMethod(class,
                        originalSelector,
                        method_getImplementation(swizzledMethod),
                        method_getTypeEncoding(swizzledMethod));
        
        if (didAddMethod) {
            class_replaceMethod(class,
                                swizzledSelector,
                                method_getImplementation(originalMethod),
                                method_getTypeEncoding(originalMethod));
        } else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
        
    });
}

第二步,把目標(biāo)代理對象所屬類的代理方法實(shí)現(xiàn)換成我們自己寫的方法實(shí)現(xiàn)。

UIWebViewDelegateHook.m

+ (void)exchangeUIWebViewDelegateMethod:(Class)aClass
{
    p_exchangeMethod(aClass, @selector(webViewDidStartLoad:), [self class], @selector(replaced_webViewDidStartLoad:));
    p_exchangeMethod(aClass, @selector(webViewDidFinishLoad:), [self class], @selector(replaced_webViewDidFinishLoad:));
    p_exchangeMethod(aClass, @selector(webView:didFailLoadWithError:), [self class], @selector(replaced_webView:didFailLoadWithError:));
    p_exchangeMethod(aClass, @selector(webView:shouldStartLoadWithRequest:navigationType:), [self class], @selector(replaced_webView:shouldStartLoadWithRequest:navigationType:));
}

- (BOOL)replaced_webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSLog(@"shouldStartLoadWithRequest");
    return [self replaced_webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
}

- (void)replaced_webViewDidStartLoad:(UIWebView *)webView
{
    NSLog(@"webViewDidStartLoad");
    [self replaced_webViewDidStartLoad:webView];
}

- (void)replaced_webViewDidFinishLoad:(UIWebView *)webView
{
    NSLog(@"webViewDidFinishLoad");
    [self replaced_webViewDidFinishLoad:webView];
    NSString *pageTitle = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    [[NSNotificationCenter defaultCenter] postNotificationName:PAFWebViewPageTitleDidChange object:self userInfo:@{PAFPageTitle:pageTitle}];
}

- (void)replaced_webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    NSLog(@"didFailLoadWithError");
    [self replaced_webView:webView didFailLoadWithError:error];
}

注意防止 setDelegate 被調(diào)用多次,這樣會導(dǎo)致方法又被換掉。

static void p_exchangeMethod(Class originalClass, SEL originalSel, Class replacedClass, SEL replacedSel)
{
    static NSMutableArray *classList = nil;
    if (classList == nil) {
        classList = [NSMutableArray array];
    }
    NSString *className = [NSString stringWithFormat:@"%@__%@", NSStringFromClass(originalClass), NSStringFromSelector(originalSel)];
    for (NSString *item in classList) {
        // 防止 setDelegate 方法被調(diào)用多次,導(dǎo)致代理方法又被換掉
        if ([className isEqualToString:item]) {
            return;
        }
    }
    
    [classList addObject:className];
    
    Method originalMethod = class_getInstanceMethod(originalClass, originalSel);
    assert(originalMethod);
    
    Method replacedMethod = class_getInstanceMethod(replacedClass, replacedSel);
    assert(replacedMethod);
    IMP replacedMethodIMP = method_getImplementation(replacedMethod);
    
    BOOL didAddMethod =
    class_addMethod(originalClass,
                    replacedSel,
                    replacedMethodIMP,
                    method_getTypeEncoding(replacedMethod));
    
    if (didAddMethod) {
        NSLog(@"class_addMethod failed --> (%@)", NSStringFromSelector(replacedSel));
    } else {
        NSLog(@"class_addMethod succeed --> (%@)", NSStringFromSelector(replacedSel));
    }
    
    Method newMethod = class_getInstanceMethod(originalClass, replacedSel);
    
    method_exchangeImplementations(originalMethod, newMethod);
}

參考 : Objective-C的hook方案(一): Method Swizzling

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容