iOS Hook WebViewのエージェントメソッド

5412 ワード

最近、DCloudチームが開発したHTML 5+を使ってHybridアプリケーションを開発しています.iOSシステムの元のUIWebViewとWKWebViewを使用してリソースをロードします.私たちのアプリケーションには、webviewがページをロードしたり、ページをロードしたりする前に何かを加える必要があります.たとえば、ページをロードした後、HTMLのtitleタグに基づいてナビゲーションバータイトルを設定します.
オリジナルはページロードサイクルに手を出そうとするが,エージェントメソッドに頼るしかない.しかし、ソースコードを修正することができないので、他の方法を探すしかありません.主な考え方は,Method Swizzleを用いてエージェントオブジェクトを見つけてエージェントメソッドを置き換えることで実現する.
UIWebViewを例にとると、具体的な操作は以下の通りです.
最初のステップは、setDelegateの実装を交換することによって、ターゲットエージェントオブジェクトが属するクラスを見つけることです.
UIWebView+Intercepter.m

- (void)p_setDelegate:(id)delegate
{
    [self p_setDelegate:delegate];
    Class delegateClass = [self.delegate class];
    //       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);
        }
        
    });
}

第2ステップでは,ターゲットエージェントオブジェクトが属するクラスのエージェントメソッド実装を我々自身が書いたメソッド実装に置き換える.
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が複数回呼び出されないようにすると、メソッドが変更されます.
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        ,          
        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