swiftxcodepush-notificationimplementsdidreceiveremotenotification

Implement method only if boolean is true (application:didReceiveRemoteNotification)


I'm trying to build my own library and I'd like to know if there is a way to only implement in my code a method if a certain boolean is true. It would be something similar to @available(iOS 14, *), but using a boolean declared in my class.

The problem comes in the implementation of the pushes. I have a variable in my main AppDelegate which I would like to config with inheritance. I have a boolean 'pushNotificationsEnabled' that establish if I want in this project pushes or not:

if pushNotificationsEnabled {
    UNUserNotificationCenter.current().requestAuthorization(options: [.sound, .alert, .badge], completionHandler: { (_, _) in })
    application.registerForRemoteNotifications()
    UNUserNotificationCenter.current().delegate = self        
}

But I can't do this logic with the didReceiveRemoteNotification method, because I have to hardcode it. Being implemented (although it is never called), Xcode drops this text in the log:

*You've implemented -[ application:didReceiveRemoteNotification:fetchCompletionHandler:], but you still need to add "remote-notification" to the list of your supported UIBackgroundModes in your Info.plist. *

It's actually right, the method is being implemented, and Xcode doesn't have to know if it's going to be used or not.

I would like to know if it is possible to do the logic that I want, that the mentioned method is only implemented if the boolean is true. Or if there is some more correct way to do it than with a boolean, that might be the option I should take.

Regards, and thanks to all!


Solution

  • This can't be done with a runtime value (how would this work if pushNotificationsEnabled were changed during the run of the program?) What you want is a compile-time value, which is supported by an #if directive.

    #if PUSH_NOTIFICATIONS_ENABLED
       ... push notification code ...
    #endif
    

    You would then add PUSH_NOTIFICATIONS_ENABLED to SWIFT_ACTIVE_COMPILATION_CONDITIONS in Xcode, or using the .define() setting in Package.swift.