0
votes

So It's my first time when I try to implement notification on an app ..I've managed to receive it and see it in userInfo but I don't receive it as an alert from the top as I receive it from the cloud messaging from Firebase.

import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
import UserNotifications
import Firebase
import FirebaseMessaging
import NotificationCenter
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)



        FirebaseApp.configure()

        let userToken = userDefaults.value(forKey: "user_token")
        if userToken == nil {
            //User is logged in
            showLoginVC()
        }
        else {
            //Show login Screen
            showHomeVC()

            Helper.registerDevice()
        }
        return true
    }

    func showLoginVC() {

        FBSDKLoginManager().logOut()

        let loginViewController = storyboard.instantiateViewController(withIdentifier: "loginVC")

        appDelegate.window = UIWindow(frame: UIScreen.main.bounds)
        appDelegate.window?.rootViewController = loginViewController
        appDelegate.window?.makeKeyAndVisible()
    }

    func showHomeVC() {

//        let voiceMoRecents = storyboard.instantiateViewController(withIdentifier: "MainVC")
//                appDelegate.window = UIWindow(frame: UIScreen.main.bounds)
//                appDelegate.window?.rootViewController = voiceMoRecents
//                appDelegate.window?.makeKeyAndVisible()

        let swRevealViewController = storyboard.instantiateViewController(withIdentifier: "SWRevealViewController")

        appDelegate.window = UIWindow(frame: UIScreen.main.bounds)
        appDelegate.window?.rootViewController = swRevealViewController
        appDelegate.window?.makeKeyAndVisible()

        if userDefaults.value(forKey: "deviceToken") == nil {
            // MARK:  PushNotification
            registerForPushNotifications()
            UNUserNotificationCenter.current().delegate = self
            GlobalMainQueue.async {
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }

    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.
        FBSDKAppEvents.activateApp()
    }

    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:.
    }

    // MARK:  Facebook Login
    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        return FBSDKApplicationDelegate.sharedInstance().application(app, open: url, options: options)
    }


    // MARK:  PUSH NOTIFICATION FUNCTIONS

    func registerForPushNotifications() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
            (granted, error) in
            print("Permission granted: \(granted)")

            guard granted else { return }
            self.getNotificationSettings()
        }
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        if let instanceIdToken = InstanceID.instanceID().token() {
            print("Device token which is good to use with FCM \(instanceIdToken)")
            userDefaults.setValue(instanceIdToken, forKey: "deviceToken")
        }

        if userDefaults.value(forKey: "callToRegisterDevice") != nil {
            Helper.registerDevice()
            userDefaults.removeObject(forKey: "callToRegisterDevice")
        }
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Fail to register for remote nottification \(error)")
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

        print(" Entire message \(userInfo)")
        print("Article avaialble for download: \(userInfo)")

        let state : UIApplicationState = application.applicationState
        switch state {
        case UIApplicationState.active:
            print("If needed notify user about the message")
        case UIApplicationState.inactive:
            print("UIApplicationState.inactive")
        case UIApplicationState.background:
            print("UIApplicationState.background")
        default:
            print("Run code to download content")
        }

        completionHandler(UIBackgroundFetchResult.newData)
    }

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


    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
         */
        let container = NSPersistentContainer(name: "VoiceMe")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
}

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
    // iOS10+, called when presenting notification in foreground
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        print("[UserNotificationCenter] applicationState:  willPresentNotification: \(userInfo)")
        //TODO: Handle foreground notification
        completionHandler([.alert])
    }

    // iOS10+, called when received response (default open, dismiss or custom action) for a notification
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        print("[UserNotificationCenter] applicationState:  didReceiveResponse: \(userInfo)")
        //TODO: Handle background notification
        completionHandler()
    }
}

extension AppDelegate : MessagingDelegate {
    func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
        NSLog("[RemoteNotification] didRefreshRegistrationToken: \(fcmToken)")
    }
}


    class func registerDevice() {
    if let deviceToken = userDefaults.value(forKey: "deviceToken") as? String {
        let callUrl = URL(string: Helper.apiUrl + "auth/register-device")
        let appVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"]
        let data2send: Dictionary<String, Any> = ["device_token" : deviceToken,
                                                  "user_token" : userDefaults.value(forKey: "user_token") as! String,
                                                  "source":"ios",
                                                  "version":"\(String(describing: appVersion!))"]

        Alamofire.request(callUrl!, method: .post, parameters: data2send).validate().responseJSON { response in
            print(response)
            if response.result.isSuccess {
                let resultObj = JSON(response.result.value!)
                if let _ = resultObj["data"].rawString(){
                    DispatchQueue.main.async {
                        print("device registered successfully")
                    }
                }
            } else {
                print("Error : \(String(describing: response.error))")
            }
        }
    } else {
        userDefaults.setValue("yes", forKey: "callToRegisterDevice")
    }
}

Possible to have redundant code..not really necessary

From console:

Entire message [AnyHashable("data"): {"duration":"1346","updated_at":"2018-05-04 18:53:54","status_type":2,"conversation_id":"8","owner_id":13,"status_name":"Read","message_token":"2018050421535268819","created_at":"2018-05-04 18:53:54","message_id":156,"url":"https://voicemo.site/media/files/8/201805042153526881915613.amr"}, AnyHashable("push_id"): ios_fIpMjYVprDSxrp3LWbV4QOIms452WUsT, AnyHashable("gcm.message_id"): 0:1525460034407947%cef2e812cef2e812, AnyHashable("notification_type"): message, AnyHashable("params"): {"color":"#009687","conversation_id":"8","subject":"new voice message","sound":"default","icon":"https://voicemo.site/media/photos/users/img_2c9b5.jpg","title":"CabuZZ"}, AnyHashable("aps"): { "content-available" = 1; }]

1
"I don't receive it as an alert from the top" - Do you mean by when you are in foreground, you don't receive any alert/ UI for incoming notification? - Ankit Jayaswal
exactly.. and background also.. - Mohamed Lee

1 Answers

1
votes

1) When app is in background:

Correct format to appear notification when app is in background is in aps dictionary as:

{
  "aps": {
      "alert": {
          "title": "",
          "subtitle": "",
          "body": “”
      },
      "badge": 1,
      "sound": "default",
      "content-available": 1,
  }
  // Other data here...
}

So, in your case update the payload for aps key as:

  "aps": {
      "alert": {
          "title": "CabuZZ",
          "body": “new voice message”
      },
      "badge": 1,
      "sound": "default",
      "content-available": 1,
  }

2) When app is in foreground:

You will receive the data in userInfo in following function, you need to show and handle the view manually. iOS will not present the view when app is in foreground.

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {

    // Handle your view here (app in foreground)

}