Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: Push notification callback on iOS not always triggerd when app is in background #253

Open
malua opened this issue Nov 7, 2024 · 0 comments

Comments

@malua
Copy link

malua commented Nov 7, 2024

We now have a simliar issue on iOS as we had on Android (#239).

Although this time, the onPushNotification callback does not trigger most of the time, when the app is openend in the background and it only happens on iOS.

import BranchSDK
import Capacitor
import CleverTapSDK
import RollbarNotifier
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    let CTDidReceiveNotification = Notification.Name("CTDidReceiveNotification")
    let CTRemoteNotificationDidRegister = Notification.Name("CTRemoteNotificationDidRegister")
    let CTRemoteNotificationRegisterError = Notification.Name("CTRemoteNotificationRegisterError")
    let CTHandleOpenURLNotification = Notification.Name("CTHandleOpenURLNotification")

    var window: UIWindow?

    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        // Override point for customization after application launch.
        if let path = Bundle.main.path(forResource: "Info", ofType: "plist"),
            let plist = NSDictionary(contentsOfFile: path),
            let rollbarAccessToken = plist["RollbarAccessToken"] as? String,
            let rollbarEnvironment = plist["RollbarEnvironment"] as? String
        {
            // use rollbarAccessToken and rollbarEnvironment

            let config = RollbarConfig.mutableConfig(
                withAccessToken: rollbarAccessToken, environment: rollbarEnvironment)
            Rollbar.initWithConfiguration(config)
        }

        Branch.setUseTestBranchKey(false)  // if you are using the TEST key
        // Branch.getInstance().enableLogging() // enable logging
        Branch.getInstance().initSession(launchOptions: launchOptions)

        return true
    }

    func application(
        _ application: UIApplication,
        didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
    ) {
        let tokenBytes = deviceToken.withUnsafeBytes {
            (bytes: UnsafeRawBufferPointer) -> [UInt32] in
            let tokenBuffer = bytes.bindMemory(to: UInt32.self)
            return Array(tokenBuffer)
        }

        let token = String(
            format: "%08x%08x%08x%08x%08x%08x%08x%08x",
            CFSwapInt32BigToHost(tokenBytes[0]), CFSwapInt32BigToHost(tokenBytes[1]),
            CFSwapInt32BigToHost(tokenBytes[2]), CFSwapInt32BigToHost(tokenBytes[3]),
            CFSwapInt32BigToHost(tokenBytes[4]), CFSwapInt32BigToHost(tokenBytes[5]),
            CFSwapInt32BigToHost(tokenBytes[6]), CFSwapInt32BigToHost(tokenBytes[7]))

        let deviceTokenString = "\(token)"
        NotificationCenter.default.post(
            name: CTRemoteNotificationDidRegister, object: deviceTokenString)

    }

    func application(
        _ application: UIApplication,
        didFailToRegisterForRemoteNotificationsWithError error: Error
    ) {
        NotificationCenter.default.post(name: CTRemoteNotificationRegisterError, object: error)
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

    func application(
        _ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]
    ) -> Bool {
        // Called when the app was launched with a url. Feel free to add additional processing here,
        // but if you want the App API to support tracking app url opens, make sure to keep this call

        Branch.getInstance().application(app, open: url, options: options)

        return ApplicationDelegateProxy.shared.application(app, open: url, options: options)
    }

    func application(
        _ application: UIApplication, continue userActivity: NSUserActivity,
        restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void
    ) -> Bool {
        // Called when the app was launched with an activity, including Universal Links.
        // Feel free to add additional processing here, but if you want the App API to support
        // tracking app url opens, make sure to keep this call

        Branch.getInstance().continue(userActivity)

        return ApplicationDelegateProxy.shared.application(
            application, continue: userActivity, restorationHandler: restorationHandler)
    }

    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        didReceive response: UNNotificationResponse,
        withCompletionHandler completionHandler: @escaping () -> Void
    ) {

        /**
         Use this method to perform the tasks associated with your app’s custom actions. When the user responds to a notification, the system calls this method with the results. You use this method to perform the task associated with that action, if at all. At the end of your implementation, you must call the completionHandler block to let the system know that you are done processing the notification.

         You specify your app’s notification types and custom actions using UNNotificationCategory and UNNotificationAction objects. You create these objects at initialization time and register them with the user notification center. Even if you register custom actions, the action in the response parameter might indicate that the user dismissed the notification without performing any of your actions.

         If you do not implement this method, your app never responds to custom actions.

         see https://developer.apple.com/reference/usernotifications/unusernotificationcenterdelegate/1649501-usernotificationcenter
         
         **/
       
            NotificationCenter.default.post(
                name: self.CTDidReceiveNotification, object: response.notification.request.content.userInfo)
       
        completionHandler()

    }

    /** For iOS 10 and above - Foreground**/

    func userNotificationCenter(
        _ center: UNUserNotificationCenter, willPresent notification: UNNotification,
        withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void
    ) {

        /**
         Use this method to perform the tasks associated with your app's custom actions. When the user responds to a notification, the system calls this method with the results. You use this method to perform the task associated with that action, if at all. At the end of your implementation, you must call the completionHandler block to let the system know that you are done processing the notification.

         You specify your app's notification types and custom actions using UNNotificationCategory and UNNotificationAction objects.
         You create these objects at initialization time and register them with the user notification center. Even if you register custom actions, the action in the response parameter might indicate that the user dismissed the notification without performing any of your actions.

         If you do not implement this method, your app never responds to custom actions.

         see https://developer.apple.com/reference/usernotifications/unusernotificationcenterdelegate/1649501-usernotificationcenter
         **/

        // call clevertap plugin to track notification and show it, but do not inform clevertap plugin
        // otherwise user would be routed somewhere without actually clicking the push notification
        
            NotificationCenter.default.post(
                name: self.CTDidReceiveNotification, object: notification.request.content.userInfo)

        completionHandler([.badge, .sound, .alert])
    }

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant