DEV Community


Posted on

Use obj-c method swizzling in GoMobile iOS games

We have used gomobile to develop games for Android and iOS. But it's not easy to add new features like integrating Ads/Analytics. On Android, we can just unpack the Apk built with gomobile and use the .so directly in a new android project. But on iOS, it's impossible. I have written a post about how to integrate ads SDK weeks ago, you can found it here. In the post, I changed the gomobile's source code and patched with two hook method. These days, I found a new way, need no change of the source code, it's the magic of Object-C, called Method Swizzling.

Method swizzling provide a way to exchange the implementation a method, so, you can use it to add new feature to an existing class. Here is what we do:

@implementation GoAppAppController(AD)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];

        SEL originalSelector = @selector(viewDidLoad);
        SEL swizzledSelector = @selector(kkViewDidLoad);

        Method originalMethod = class_getInstanceMethod(class, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);

        BOOL success = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
        if (!success) {
            method_exchangeImplementations(originalMethod, swizzledMethod);

- (void)kkViewDidLoad {
    [self kkViewDidLoad];

    // Initialize Google Mobile Ads SDK
    [GADMobileAds configureWithApplicationID:@"..."];
Enter fullscreen mode Exit fullscreen mode

In the + (void)load method, I use method swizzling to exchange the implementation of GoAppAppController's viewDidLoad method and my kkViewDidLoad method. GoAppAppController is gomobile's implementation of UIViewController, you can found the source code in x/mobile/app/darwin_ios.m. In kkViewDidLoad method, I call [self kkViewDidLoad] to invoke the original viewDidLoad , than, call GADMobileAds to initialize my Admob Ads SDK.

That's all, it's very concise and easy! I also used it in my second game Unstable Tower, but, unfortunately, Apple say it's alike existing game in AppStore, so it did not pass the review. There is also an Android version, if you like it, you can download it in GooglePlay.

Top comments (0)