Implement unhandled protocol method in extension

158 Views Asked by At

I'm trying to implement some push notification methods in my Cordova plugin. Cordova creates their own UIApplicationDelegate, called CDVAppDelegate, so I tried to extend that and use swizzling to add my methods.

However, when I implement an optional protocol method that is unimplemented in CDVAppDelegate, and use swizzling to make it available, this new method isn't called. If I hack the CDVAppDelegate code to implement this method, the new method does get called.

Here are some code snippets - hopefully that will help clarify the situation:

In CDVAppDelegate.h

@interface CDVAppDelegate : NSObject <UIApplicationDelegate>{}

In CDVAppDelegate.m

@implementation CDVAppDelegate

// added by me
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    return;
}

In my "extension CDVAppDelegate {...}"

@objc func swizzled_application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    NSLog("\(TAG) APNs token retrieved: \(deviceToken)")
    self.swizzled_application(application, didRegisterForRemoteNotificationsWithDeviceToken:deviceToken) // swizzled, so this calls original
    ...
}

How can I get this working without modifying CDVAppDelegate.m?

1

There are 1 best solutions below

1
Crag On

The method class_addMethod lets me implement the unimplemented methods. You can call this and fallback on method_exchangeImplementations if it doesn't work (if the selector already has a method implementation).