I was using AppDelegate to ask the user about notification permission once the app starts working. then I realized it's not the best user experience. so I moved the code to a customized view controller to ask for permission only when it's required. here's my code
public static func requestNofiticationPermission(completionHanlder : @escaping (Bool) -> Void){
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = UIApplication.shared.delegate as! AppDelegate
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { (success, error) in
completionHanlder(success)
})
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
}
UIApplication.shared.registerForRemoteNotifications()
}
AppDelegate code
// [START receive_message]
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
handleNotification(userInfo: userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
handleNotification(userInfo: userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
// print notification data
func handleNotification(userInfo: [AnyHashable: Any]){
let gcmMessageIDKey = "gcm.message_id"
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
var body : String!
var title : String?
if let aps = userInfo["aps"] as? [String : Any] {
if let alert = aps["alert"] as? [String : String] {
body = alert["body"]
title = alert["title"]
}
}
print("title: \(title)")
print("body: \(body)")
}
as you can see, I kept message handling in AppDelegate and referred to it in code like this UIApplication.shared.delegate
. for some reason, it stopped handling the messages. the functions weren't triggered