美文网首页
iOS Tweak 进程间通讯

iOS Tweak 进程间通讯

作者: 学无止境吧 | 来源:发表于2017-02-04 11:49 被阅读2064次

    写tweak的时候,经常需要tweak进程间通讯。因为hook的应用经常都是在沙盒里的,如果需要操作沙盒外的文件,比如记录日志什么的,就不行。
    怎么处理呢?
    就是在有权限的地方,比如SpringBoard,或者守护进程里,起一个服务。在沙盒里,发送一个通知,然后被服务捕获到。在服务里处理逻辑。

    这里我们讲一下基于rocketbootstrap的进程间通讯。
    rocketbootstrap是别人已经封装好的工具,我们可以直接拿来用。
    参照文档:
    http://iphonedevwiki.net/index.php/Updating_extensions_for_iOS_7

    废话不多说,直接写demo。

    首先,建立一个iOS OpenDev的tweak项目,导入。


    这些文件可以直接在github上获取。
    头文件:https://github.com/rpetrich/RocketBootstrap/tree/master

    dylib我是直接在手机里提取的, 在cydia中安装RocketBootstrap之后,直接可以找到
    文件路径:/usr/lib/librocketbootstrap.dylib

    接下来写xm文件。
    首选在SpringBoard中,将RocketBootstrap的服务起了。
    具体代码:

    #TweakDemo.xm
    #import "rocketbootstrap.h"
    
    #define kXPCCenterNameKey  @"kXPCCenterNameKey_83641"
    
    %hook SpringBoard
    - (void)applicationDidFinishLaunching:(id)application {
       %orig;
       CPDistributedMessagingCenter *c = [%c(CPDistributedMessagingCenter) centerNamed:kXPCCenterNameKey];
       rocketbootstrap_distributedmessagingcenter_apply(c);
       [c runServerOnCurrentThread];
       [c registerForMessageName:@"myMessageName" target:self selector:@selector(handleMessage:withUserInfo:)];
       NSLog(@"注册监听 start");
    }
    
    %new
    - (void)handleMessage:(NSString *)name withUserInfo:(NSDictionary *)userInfo {
       NSLog(@"handleMessage withUserInfo:%@",userInfo);
       //TODO:something
    }
    
    %end
    

    在需要发送的地方,如此这般的写:

    %hook SomeClass
    
    -(void)someMethod{
       %orig;
        NSMutableDictionary *userInfo = [@{} mutableCopy];
        [userInfo setObject:@"123" forKey:@"arg001"];
        [userInfo setObject:@"456" forKey:@"arg002"];
        NSLog(@"发送: %@=%@",kXPCCenterNameKey,userInfo);
        CPDistributedMessagingCenter *c = [%c(CPDistributedMessagingCenter) centerNamed:kXPCCenterNameKey];
        rocketbootstrap_distributedmessagingcenter_apply(c);
        [c sendMessageName:@"myMessageName" userInfo:userInfo];
    }
    
    %end
    

    因为我们的tweak是依赖RocketBootstrap的,所以需要在control文件里面配置一下Depends:

    Depends: firmware (>= 5.0), mobilesubstrate,com.rpetrich.rocketbootstrap (>= 1.0.2) | firmware (<< 7.0)
    

    跑一下试试看,祝你成功。

    相关文章

      网友评论

          本文标题:iOS Tweak 进程间通讯

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