美文网首页iOS 开发每天分享优质文章
iOS对静态库的网络请求函数进行hook

iOS对静态库的网络请求函数进行hook

作者: freesan44 | 来源:发表于2023-10-26 11:31 被阅读0次

    问题

    要对第三方厂商SDK的.a静态库中某些网络请求进行替换操作

    解决方案

    1. 因为第三方厂商SDK中的网络请求框架不对外开放,所以通过对.a库使用Hopper Disassembler进行分析,定位到是使用什么函数进行请求

    2. 建立一个方法,对.a中的网络框架方法进行swizzling

       Class systemClass = NSClassFromString(@"XXXNetURLSessionManager");
        
        SEL sel_System = @selector(dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:);
        SEL sel_Custom = @selector(hook_dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:);
        
        Method method_System = class_getInstanceMethod(systemClass, sel_System);
        Method method_Custom = class_getInstanceMethod([self class], sel_Custom);
        
        IMP imp_System = method_getImplementation(method_System);
        IMP imp_Custom = method_getImplementation(method_Custom);
        
        if (class_addMethod(systemClass, sel_Custom, imp_System, method_getTypeEncoding(method_System))) {
            class_replaceMethod(systemClass, sel_System, imp_Custom, method_getTypeEncoding(method_System));
        } else {
            method_exchangeImplementations(method_System, method_Custom);
        }
    
    1. 在hook方法中,通过GCD,发起自身的网络请求,等返回结果后进行参数映射后再return
    - (NSURLSessionDataTask *)hook_dataTaskWithRequest:(NSURLRequest *)request uploadProgress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock downloadProgress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler {
        // 创建一个信号量
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
        // 异步操作
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            // 在这里执行您的异步操作,比如网络请求
            // 当异步操作完成后,调用 completionHandler 返回结果
            
            // 假设您的异步操作是一个网络请求
            NSURLSessionDataTask *dataTask = [NSURLSession.sharedSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                // 处理异步操作的结果
                // ...
                
                // 调用 completionHandler 返回结果
                completionHandler(response, responseObject, error);
                
                // 发送信号,解除阻塞
                dispatch_semaphore_signal(semaphore);
            }];
            
            [dataTask resume];
        });
    
        // 阻塞当前线程,等待信号
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
        // 返回结果
        return [self hook_dataTaskWithRequest:request uploadProgress:uploadProgressBlock downloadProgress:downloadProgressBlock completionHandler:completionHandler];
    }
    

    相关文章

      网友评论

        本文标题:iOS对静态库的网络请求函数进行hook

        本文链接:https://www.haomeiwen.com/subject/xlbyidtx.html