Search code examples
iosswiftapple-push-notificationsforeground

IOS push notifications in foreground Swift 4.2


I am working on IOS application where I am working on Push Notifications by using Parse SDK. I am able to get the notifications when my back is in background. Now I want to receive Notifications even if my App is in foreground. I have searched many code for it but it didn't suites in my current AppDelegate class.

How to get Push Notifications even if my app is in foreground?

 @UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Thread.sleep(forTimeInterval: 3.0)
        // Override point for customization after application launch.

        let configuration = ParseClientConfiguration {
            $0.applicationId = "asdasdasd"
            $0.clientKey = "asdasdasdas"
            $0.server = "https://parseapi.back4app.com"
        }
        Parse.initialize(with: configuration)

        UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate

        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
            (granted, error) in
            print("Permission granted: \(granted)")
            guard granted else { return }
            self.getNotificationSettings()
        }

        return true
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
    {
        completionHandler([.alert, .badge, .sound])
    }

    func getNotificationSettings() {
        UNUserNotificationCenter.current().getNotificationSettings { (settings) in
            print("Notification settings: \(settings)")
            guard settings.authorizationStatus == .authorized else {
                return
            }
            DispatchQueue.main.async(execute: {
                UIApplication.shared.registerForRemoteNotifications()
            })
        }
    }

    func application(_ application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        createInstallationOnParse(deviceTokenData: deviceToken)
    }


    func applicationWillResignActive(_ application: UIApplication) {

    }

    func applicationDidEnterBackground(_ application: UIApplication) {

    }

    func applicationWillEnterForeground(_ application: UIApplication) {

    }

    func applicationDidBecomeActive(_ application: UIApplication) {

    }

    func applicationWillTerminate(_ application: UIApplication) {

    }

    func application(_ application: UIApplication,
                     didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Failed to register: \(error)")
    }
    }
}

I have found this solution from same forum but I am not able to put the following code snippet in my current Code:

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo


        // Print full message.
        print("tap on on forground app",userInfo)

        completionHandler()
    }

Solution

  • Since iOS 10, apple allow users to handle Push Notification presentation while in foreground. you can handle that in willPresent method. and handle the Push Notification in the completionHandler, pass your desired options i.e. alert, badge and sound.

    Confirm you appDelegate to use UNUserNotificationCenterDelegate

    put this in your didFinishLaunchingWithOptions method

    UNUserNotificationCenter.current().delegate = self
    

    Before

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
                (granted, error) in
                print("Permission granted: \(granted)")
                guard granted else { return }
                self.getNotificationSettings()
            }
    

    And add this method

     func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
        {
            completionHandler([.alert, .badge, .sound])
        }
        
    

    iOS 14 Update .alert has been depreciated, you should now use .banner, like so:

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
           {
            completionHandler([.banner, .badge, .sound])
           }