FCM Notifications are received in background but not foreground on iOS - swift

I am getting FCM messages pushed to my iOS device fine when in the background but not in the foreground. I have found a number of articles where others had the same issue and solved it by adding the willPresentNotification function. However this isn't solving the issue for me. My FCM code is as follows:
class FCMManager: NSObject, MessagingDelegate, UNUserNotificationCenterDelegate {
static let shared = FCMManager()
let database = Database.database().reference()
public func registerForPushNotifications() {
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .sound, .announcement, .badge, .carPlay, .providesAppNotificationSettings]
UNUserNotificationCenter.current()
.requestAuthorization( options: authOptions,
completionHandler: { granted, _ in
guard granted else {
print("Apple push notifications are not registered")
return
}
print("Apple push notifications are registered")
})
Messaging.messaging().delegate = self
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
updatePushTokenIfNeeded()
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
updatePushTokenIfNeeded()
}
}
My notification payloads are set up as:
["to" : "fcm_token",
"notification" : ["title" : "Message Title",
"body" : "Message Body",
"sound" : "default",
"badge" : 1]
]
Then my app delegate is as follows:
class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
let notificationCenter = UNUserNotificationCenter.current()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
let fcmManager = FCMManager()
fcmManager.registerForPushNotifications()
return true
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
if #available(iOS 14, *) {
completionHandler([.banner])
} else {
completionHandler([.alert])
}
}
}

Related

iOS Firebase push notification not working but working on pusher

Problem:
Cannot receive push notification for my from firebase given the fact that I was able to receive the device token and firebase token.
Here are my main calls in my AppDelegate.swift
UIApplication.shared.registerForRemoteNotifications()
This call is successful and I am able to establish connection to APNS because I was able to get my token with this call:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
Also, I know I am connecting to firebase because I am able to get my firebase token with this call:
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String)
So I am pretty confident that my code in AppDelegate.swift is fine.
Here are my steps to configure firebase push notification:
Downloaded my google-service.plist file and dragged it into my project
Logged into my apple developers account (paid) and created my Key with push notification (copied down the KeyID and along with my teamID or App prefix).
Went into my firebase account and uploaded my Key along with my KeyID and TeamID
I made sure my app capabilities got the push notification switch to ON
Tried sending a test message and app never receives one
My AppDelegate.swift:
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
UIApplication.shared.applicationIconBadgeNumber = 0
// Override point for customization after application launch.
loggingWithSwitftyBeaverConfiguration()
UNUserNotificationCenter.current().delegate = self
// requesting user's permission to accpet push notification
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted == true {
log.debug("User granted push notification")
UNUserNotificationCenter.current().delegate = self
Messaging.messaging().delegate = self
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
} else {
log.debug("User did not grant pn")
}
}
return true
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
log.debug("Device token receiving failed because: \(error.localizedDescription)")
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.map {String(format: "%02.2hhx", $0)}.joined()
log.debug("Token: \(token)")
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
log.debug("\(remoteMessage.description)")
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
log.debug("Firebase cloud messaging token: \(fcmToken)")
}
func applicationDidBecomeActive(_ application: UIApplication) {
Messaging.messaging().shouldEstablishDirectChannel = true
}
func applicationDidEnterBackground(_ application: UIApplication) {
Messaging.messaging().shouldEstablishDirectChannel = false
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
UIApplication.shared.applicationIconBadgeNumber += 1
print("push notification received")
}
}
Extra information: I was able to receive test notifications by using pusher, just wanted to throw it out there,
Thank you
UPDATE: - working code:
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var compositionRoot: CompositionRoot?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow()
configureCompositionRoot()
configureFirebase()
configurePushNotification()
configureApplicationEntryPoint()
configureLogging()
return true
}
func configureCompositionRoot() {
guard let window = window else { return }
compositionRoot = CompositionRoot(window: window)
}
func configureApplicationEntryPoint() {
guard let compositionRoot = compositionRoot else { return }
compositionRoot.getCoordinator().onStart()
}
func configureLogging() {
let console = ConsoleDestination()
log.addDestination(console)
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.map {String(format: "%02.2hhx", $0)}.joined()
print("Token: \(token)")
Messaging.messaging().apnsToken = deviceToken
//Messaging.messaging().setAPNSToken(deviceToken, type: MessagingAPNSTokenType.prod)
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
func configureFirebase() {
FirebaseApp.configure()
}
func configurePushNotification() {
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { (granted, error) in
if granted == true {
print("User granted push notification")
UNUserNotificationCenter.current().delegate = self
Messaging.messaging().delegate = self
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
} else {
print("User did not grant pn")
}
}
}
}
extension AppDelegate: MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
}
}
Please check your payload. It might be the reason that you are not receiving notifications.
Your payload should like:
{
"to": "APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...",
"notification": {
"body": "great match!",
"title": "Portugal vs. Denmark",
"icon": "myicon"
},
"data": {
"Nick": "Mario",
"Room": "PortugalVSDenmark"
}
}
Having all data under data does not trigger any notification in iOS even though Firebase returns a successful request because the forwarded APNS payload is not correct. Besides the proper way should be to follow the GCM or FCM payload recommendations, which is to use both notification for the notification message and data for custom key/value pairs.
When FCM Send data to APNS it convert it into APNs payload. It set values of notification in aps tag i.e.
{
"aps" : {
"alert" : {
"title" : "Portugal vs. Denmark",
"body" : "Portugal vs. Denmark",
}
},
"Nick" : "Mario",
"Room" : "PortugalVSDenmark"
}
[Follow the step by step process define here..]
https://firebase.google.com/docs/cloud-messaging/ios/client
Another possible lead is to disable Firebase Swizzling as explained here :
https://firebase.google.com/docs/cloud-messaging/ios/client

FCM push notification not showing when app is open in swift 3

I want to show fcm message any time if my app is open or not open.I want to catch message and save core data.when my app is opened I will get my message but notification alert doesn't show. But when I close my app it shows my message but I did not get my message in background.. here is my appDelegate
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate , UNUserNotificationCenterDelegate,MessagingDelegate{
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
// For iOS 10 data message (sent via FCM
Messaging.messaging().remoteMessageDelegate = self
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
FirebaseApp.configure()
return true
}
//MARK: FCM Token Refreshed
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
// FCM token updated, update it on Backend Server
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Messaging",messaging)
print("remoteMessage*******************",remoteMessage)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (_ options: UNNotificationPresentationOptions) -> Void) {
print("Handle push from foreground")
// custom code to handle push while app is in the foreground
print("\(notification.request.content.userInfo)")
if UIApplication.shared.applicationState == .active { // In iOS 10 if app is in foreground do nothing.
print("active****")
completionHandler([])
} else { // If app is not active you can show banner, sound and badge.
print("Not active****")
completionHandler([.alert, .badge, .sound])
}
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
print("Handle push from background or closed")
print("\(response.notification.request.content.userInfo)")
}
func tokenRefreshNotification(notification: NSNotification) {
let refreshedToken = InstanceID.instanceID().token()
// print("fcm**************************","Dhruw: Connected to FCM. Token : \(String(describing: refreshedToken))")
var fcm_token = String(describing: refreshedToken!)
print("fcm toker********",fcm_token);
connectToFCM()
}
func connectToFCM() {
Messaging.messaging().shouldEstablishDirectChannel = true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "Finjo_Expense_Management")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
guard let messageId = userInfo["gcm.message_id"]
else {
return
}
print(messageId)
print("did*****",userInfo);
let aps = userInfo[AnyHashable("aps")] as? NSDictionary
var message = aps?["alert"] as! String;
print("message",message)
}
// Called when APNs has assigned the device a unique token
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Convert token to string
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
// Print it to console
print("APNs device token: \(deviceTokenString)")
//09256B251D3BBEAA50949067DF40AB75E5D2668170AB0C3B0D310205F2876C32
// Persist it in your backend in case it's new
}
// Called when APNs failed to register the device for push notifications
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
// Print the error to console (you should alert the user that registration failed)
print("APNs registration failed: \(error)")
}
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)")
}
}
}
}
With Advance thanks...Please help me
When app is open you need to set localnotification for showing notifications.. otherwise you need to show custom view.

Using URLSession and background fetch together with remote notifications using firebase

I am trying to implement a basic func here which will be called when my app is backgrounded or suspended.
In reality, we aim to send about 5 a day so Apple should not throttle our utilisation.
I've put together the following which uses firebase and userNotifications, for now, it is in my app delegate.
import Firebase
import FirebaseMessaging
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var backgroundSessionCompletionHandler: (() -> Void)?
lazy var downloadsSession: Foundation.URLSession = {
let configuration = URLSessionConfiguration.background(withIdentifier: "bgSessionConfiguration")
configuration.timeoutIntervalForRequest = 30.0
let session = Foundation.URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
return session
}()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FIRApp.configure()
if #available(iOS 10.0, *) {
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
// For iOS 10 data message (sent via FCM)
FIRMessaging.messaging().remoteMessageDelegate = self
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
let token = FIRInstanceID.instanceID().token()!
print("token is \(token) < ")
return true
}
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: #escaping () -> Void){
print("in handleEventsForBackgroundURLSession")
_ = self.downloadsSession
self.backgroundSessionCompletionHandler = completionHandler
}
//MARK: SyncFunc
func startDownload() {
NSLog("in startDownload func")
let todoEndpoint: String = "https://jsonplaceholder.typicode.com/todos/1"
guard let url = URL(string: todoEndpoint) else {
print("Error: cannot create URL")
return
}
// make the request
let task = downloadsSession.downloadTask(with: url)
task.resume()
NSLog(" ")
NSLog(" ")
}
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession){
DispatchQueue.main.async(execute: {
self.backgroundSessionCompletionHandler?()
self.backgroundSessionCompletionHandler = nil
})
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
NSLog("in didReceiveRemoteNotification")
NSLog("%#", userInfo)
startDownload()
DispatchQueue.main.async {
completionHandler(UIBackgroundFetchResult.newData)
}
}
}
#available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// Receive displayed notifications for iOS 10 devices.
/*
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// Print message ID.
//print("Message ID: \(userInfo["gcm.message_id"]!)")
// Print full message.
print("%#", userInfo)
startDownload()
DispatchQueue.main.async {
completionHandler(UNNotificationPresentationOptions.alert)
}
}
*/
}
extension AppDelegate : FIRMessagingDelegate {
// Receive data message on iOS 10 devices.
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
print("%#", remoteMessage.appData)
}
}
extension AppDelegate: URLSessionDownloadDelegate {
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL){
NSLog("finished downloading")
}
}
The results are as follows:
When the app is in the foreground:
I get the log "in startDownload func"
I get the log "finished downloading".
When the app is in the background:
I get the log "in startDownload func"
I do not get the log "finished downloading".
The silencer isn't working i.e. when the app is backgrounded, I am still getting the notification in the tray.
I am using Postman to send the request and tried the following payload, which results in the console error 'FIRMessaging receiving notification in invalid state 2':
{
"to" : "Server_Key",
"content_available" : true,
"notification": {
"body": "Firebase Cloud Message29- BG CA1"
}
}
I have the capabilities set for background fetch and remote notifications. The app is written in swift 3 and uses the latest Firebase
EDIT: Updated AppDelegate to include funcs as per comment
A few observations:
When your app is restarted by handleEventsForBackgroundURLSessionIdentifier, you have to not only save the completion handler, but you actually have to start the session, too. You appear to be doing the former, but not the latter.
Also, you have to implement urlSessionDidFinishEvents(forBackgroundURLSession:) and call (and discard your reference to) that saved completion handler.
You appear to be doing a data task. But if you want background operation, it has to be download or upload task. [You have edited question to make it a download task.]
In userNotificationCenter(_:willPresent:completionHandler:), you don't ever call the completion handler that was passed to this method. So, when the 30 seconds (or whatever it is) expires, because you haven't called it, your app will be summarily terminated and all background requests will be canceled.
So, willPresent should call its completion handler as soon it done starting the requests. Don't confuse this completion handler (that you're done handling the notification) with the separate completion handler that is provided later to urlSessionDidFinishEvents (that you're done handling the the background URLSession events).
Your saved background session completion handler is not right. I'd suggest:
var backgroundSessionCompletionHandler: (() -> Void)?
When you save it, it is:
backgroundSessionCompletionHandler = completionHandler // note, no ()
And when you call it in urlSessionDidFinishEvents, it is:
DispatchQueue.main.async {
self.backgroundSessionCompletionHandler?()
self.backgroundSessionCompletionHandler = nil
}

Not receiving APNS messages from Azure after upgrade to Swift 3.0

After updating my application to Swift 3 (what an experience that was! ) - I knew I had to rework the Notification code due to the changes in iOS10.
Using this helpful resource - I was able to recode and I am getting a valid connection
https://github.com/ashishkakkad8/Notifications10Swift/blob/master/Notifications10Swift/AppDelegate.swift
I also amended the Capabilties for the project, adding 1) Notifications, and 2) Background Modes / Remote Notifications.
However, when I send a test message thru the Azure 'test-send' feature, I don't receive it.
Here's the relevant code from my AppDelegate:
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Register for remote notifications
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
if error == nil{
UIApplication.shared.registerForRemoteNotifications()
}
}
}
else {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
let hub: SBNotificationHub = SBNotificationHub.init(connectionString: APISettings.Instance.notificationHubEndpoint, notificationHubPath: APISettings.Instance.notificationHubName)
hub.registerNative(withDeviceToken: deviceToken, tags: nil) { (error) -> Void in
if (error != nil){
print("Error registering for notifications: %#", error)
} else {
print("Registration ok")
}
}
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error)
{
print("Error = ",error.localizedDescription)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print(userInfo)
}
// MARK: UNUserNotificationCenter Delegate // >= iOS 10
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
print("User Info = ",notification.request.content.userInfo)
completionHandler([.alert, .badge, .sound])
}
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
print("User Info = ",response.notification.request.content.userInfo)
completionHandler()
}
Any help would be greatly appreciated.
Try to call this function on didFinishLaunchingWithOptions and clean >Run your app
func registerNotification()
{
UIApplication.sharedApplication()
let application = UIApplication.sharedApplication()
if application.respondsToSelector(#selector(UIApplication.registerUserNotificationSettings(_:)))
{
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
}
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
if notificationSettings.types != .None {
application.registerForRemoteNotifications()
}
}

Push not received on iOS 10 when the app is in foreground

Yesterday I updated 2 of my apps to swift 3.
func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
UIApplication.shared.registerForRemoteNotifications()
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print(error.localizedDescription)
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Save Installation if registered successfully
}
//MARK: Recieved Notification
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
print("received a notification")
}
so background push notification works fine on both apps, but in one of my app its not receiving any pushes in foreground that is, didReceiveRemoteNotification is never getting called
Things I have checked, Push Notifications enabled in Capabilities
Using this code to register for push notifications on both apps
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .alert, .sound], categories: nil))
Not only that, I have tried UNUserNotificationCenterDelegate for iOS 10 but still none of its delegate functions get called.
This only doesn't work on iOS 10 phones, iOS 8 and 9 works like charm.
So I'm not really sure why its never calling didReceiveRemoteNotification in only one of my 2 swift 3 apps on ios 10 when the app is open
This is my iOS 10 code I tried
//Added in didFinishLaunchingWithOptions
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
if error == nil{
UIApplication.shared.registerForRemoteNotifications()
}
}
}
//Delegates
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
print("push2")
}
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
print("push1")
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.initializeNotificationServices()
}
func initializeNotificationServices() -> Void {
if #available(iOS 10.0, *) {
UNUserNotificationCenter.currentNotificationCenter().delegate = self
UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Badge, .Sound, .Alert]) { (granted, error) in
if granted {
//self.registerCategory()
//self.scheduleNotification("test", interval: 3)
//self.scheduleNotification("test2", interval: 5)
let types : UIUserNotificationType = [.Badge, .Sound, .Alert]
let mySettings : UIUserNotificationSettings = UIUserNotificationSettings.init(forTypes: types, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(mySettings)
UIApplication.sharedApplication().registerForRemoteNotifications()
}
}
}
else {
// Fallback on earlier versions
let settings = UIUserNotificationSettings(forTypes: [.Sound, .Alert, .Badge], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
// This is an asynchronous method to retrieve a Device Token
// Callbacks are in AppDelegate.swift
// Success = didRegisterForRemoteNotificationsWithDeviceToken
// Fail = didFailToRegisterForRemoteNotificationsWithError
UIApplication.sharedApplication().registerForRemoteNotifications()
}
}
#available(iOS 10.0, *)
func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
print("willPresent")
completionHandler([.Badge, .Alert, .Sound])
}
#available(iOS 10.0, *)
func userNotificationCenter(center: UNUserNotificationCenter, didReceiveNotificationResponse response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) {
self.didReceiveBookingAppRemoteNotification(response.notification.request.content.userInfo)
print("didReceive == >> \(response.notification.request.content.userInfo)")
completionHandler()
}
//for Lower to ios 10 version
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
self.getNotifInfo(userInfo)
}
Make sure you have to enable push notification from project's
Target => Capabilities and you have to add it's framework UserNotifications.framework