I'm trying to have push notifications working, but I have the impression that the method "didRegisterForRemoteNotificationsWithDeviceToken" is never called, same case for "didFailToRegisterForRemoteNotificationsWithError". Some old threads here on stackoverflow show exactly the same problem, but solutions provided doesn't have worked for me :/
I have searched everywhere and it seems that I'm stuck with this problem, the token is never printed to the console, the only output I got is:
Permission granted: true
Notification settings: <UNNotificationSettings: 0x1c009cb10; authorizationStatus: Authorized, notificationCenterSetting: Enabled, soundSetting: Enabled, badgeSetting: Enabled, lockScreenSetting: Enabled, carPlaySetting: NotSupported, alertSetting: Enabled, alertStyle: Banner>
What I did:
Checked that the service is up : https://developer.apple.com/system-status/
Issued a certificate successfully for my app (APNs Development)
Running app on different devices
Imported UserNotifications.framework
Set Push Notifications and Remote notifications (Background Modes) capabilities ON
Here is my code (appdelegate.swift):
//
// AppDelegate.swift
import UserNotifications
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
registerForPushNotifications()
return true
}
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 registerForPushNotifications() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
(granted, error) in
print("Permission granted: \(granted)")
guard granted else { return }
self.getNotificationSettings()
}
}
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
print("Notification settings: \(settings)")
}
}
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenParts = deviceToken.map { data -> String in
return String(format: "%02.2hhx", data)
}
let token = tokenParts.joined()
print("Device Token: \(token)")
}
func application(_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register: \(error)")
}
}
Thank's in advance!
You never actually try registering for push notifications, hence the relevant functions are never called. You need to call UIApplication.shared.registerForRemoteNotifications() in order to receive push notifications, while your current code only requests permission for notifications.
func registerForPushNotifications() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
print("Permission granted: \(granted)")
guard granted else { return }
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
print("Notification settings: \(settings)")
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
}
Related
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
registerForPushNotifications()
return true
}
func registerForPushNotifications() {
UNUserNotificationCenter.current()
.requestAuthorization(options: [.alert, .sound, .badge]) {
[weak self] granted, error in
print("Permission granted: \(granted)")
guard granted else { return }
self!.getNotificationSettings()
}
}
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { settings in
print("Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else { return }
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
let token = tokenParts.joined()
print("Device Token: \(token)")
}
func application(
_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register: \(error)")
}
this is the code where I have implemented remote notifications registration methods.
this is what I have done so far:
I have configuring push notification by Targets -> Signing&Capabilities and correctly entered team and build indentifier.
Add the push notification capability by tapping + at the top left.
I have enabled the push notification by going into the iPhone setting.
wifi is on from the iPhone.
This is what I have tried so far to resolve this:
Restart the phone, disable and then enable wifi
Tried to change bundle identifier
Remove the push notification capability and added it again but nothing helped so far.
App asks for the permission for push notification and even after granting the permission, last two methods are not being called. what have I done wrong? I have seen other similar question and tried everything but still could not figure out what is wrong with the code.
Instead of calling registerForRemoteNotifications inside getNotificationSettings method, call it directly inside "registerForPushNotifications" after verifying requestAuthorization response "granted" is true.
You need not validate "settings.authorizationStatus == .authorized" before calling "registerForRemoteNotifications" method.
func registerForPushNotifications() {
UNUserNotificationCenter.current()
.requestAuthorization(options: [.alert, .sound, .badge]) {
[weak self] granted, error in
print("Permission granted: \(granted)")
guard granted else { return }
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
Hope this helps.
Just separate your permission logic from the remote notifications.
The call of UIApplication.shared.registerForRemoteNotifications() will always lead to didRegisterForRemoteNotificationsWithDeviceToken or didFailToRegisterForRemoteNotificationsWithError.
I would recommend
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
application.registerForRemoteNotifications()
// If you want to ask for push permissions immediately on first start (I wouldnt recommend)
UNUserNotificationCenter.current()
.requestAuthorization(options: [.alert, .sound, .badge]) { ... }
return true
}
This means you will receive the push token. You can use this token to already send pushes to the device.
However, notifications will only be displayed once the user grants .alert permission.
I had this same problem, and I fixed it with putting registerForRemoteNotifications logic after Firebase.configuration() in didFinishLaunchingWithOptions delegate method.
I only receive the notification on my test device, but on a user's device does not receive the message. What could be the error?
import UIKit
import Firebase
import IQKeyboardManagerSwift
import SVProgressHUD
import UserNotifications
#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.
window?.rootViewController = initialVC
window?.makeKeyAndVisible()
//Config. Firebase
FirebaseApp.configure()
//Config. Push Notification
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self
Messaging.messaging().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (success, error) in
if error == nil{
print("Autorizacion exitosa")
}
}
} else {
// Fallback on earlier versions
let setting : UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(setting)
}
application.registerForRemoteNotifications()
NotificationCenter.default.addObserver(self, selector: #selector(self.refreshToken(notification:)), name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)
return true
}
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.
Messaging.messaging().shouldEstablishDirectChannel = false
application.applicationIconBadgeNumber = 0
}
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.
ConnectToFCM()
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
#objc func refreshToken(notification: NSNotification){
let refreshToken = InstanceID.instanceID().token()!
print("refreshToken: \(refreshToken)")
ConnectToFCM()
}
func ConnectToFCM(){
Messaging.messaging().shouldEstablishDirectChannel = true
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
let token = Messaging.messaging().fcmToken
print("FCM token: \(token ?? "")")
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
}
}
I tried following the tutorial on Firebase's webpage to add Push Notifications to my app. I have done everything with the certificates and such, but I think something is wrong with the code.
My iPhone is not receiving any notifications when I sent them from the Firebase webpage.
What am I missing in my code?
Here is my AppDelegate.swift file:
import UIKit
import Firebase
import FirebaseMessaging
import FirebaseInstanceID
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
FIRApp.configure()
// Register for remote notifications. This shows a permission dialog on first run, to
// show the dialog at a more appropriate time move this registration accordingly.
// [START register_for_notifications]
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 })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
// [END register_for_notifications]
return true
}
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.
FIRMessaging.messaging().disconnect()
}
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: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
return TWTRTwitter.sharedInstance().application(app, open: url, options: options)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
}
I'm using Firebase to enable push notifications on iOS 11. I'm trying to ask the user's notification permission only AFTER a button is pushed.
Currently, the app asks for the users permission immediately on load. I want to ask this permission in the EnableNotificationViewController.swift class after a button is pushed.
AppDelegate.swift
import UIKit
import Firebase
import FBSDKCoreKit
import UserNotifications
import FirebaseInstanceID
import FirebaseMessaging
#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.
FirebaseApp.configure()
// [START set_messaging_delegate]
Messaging.messaging().delegate = self
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 })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
return true
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)
}
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.
FBSDKAppEvents.activateApp()
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Notifications
// The callback to handle data message received via FCM for devices running iOS 10 or above.
func application(received remoteMessage: MessagingRemoteMessage) {
print(remoteMessage.appData)
}
}
EnableLocationViewController.swift
import UIKit
import Spring
import Firebase
class EnableNotificationsViewController: UIViewController {
// MARK: - Outlets
#IBOutlet weak var textLabel: DesignableLabel!
// MARK: - View Did Load
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Actions
#IBAction func notificationButton(_ sender: UIButton) {
}
}
Well you will need to move the remote notification permission request into a method in AppDelegate and then call this method from your ViewController that is called EnableNotificationsViewController.
lets start from AppDelegate and adding registerAPNSServicesForApplication method:
///- register with APNS
func registerAPNSServicesForApplication(_ application: UIApplication,withBlock block: #escaping (_ granted:Bool) -> (Void)) {
// [START register_for_notifications]
if #available(iOS 10.0, *) {
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {granted, error in
if granted == true{
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
}
block(granted)
})
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
}
And then from your EnableNotificationsViewController call the method in AppDelegate to request the permission, And just so you know that iOS 10 and up you will have completion block of the permission if its granted or not and i made it so it will be returned in completion block into your view controller, but not for iOS 9 and below, You'll need a special handling:
// MARK: - Actions
#IBAction func notificationButton(_ sender: UIButton) {
let myApplication = UIApplication.shared.delegate as! AppDelegate
myApplication.registerAPNSServicesForApplication(UIApplication.shared) { (granted) -> (Void) in
if #available(iOS 10.0, *) {
if granted {
}else {
}
}else {
// will not be returned because iOS 9 has no completion block for granting the permission it will require special way.
}
}
}
To be honest i don't have device with iOS 9 to simulate completion block, but i think the users for iOS 9 and below are just 10% according to Apple Analytics for November 2017
That should do it :)
So I just implemented (well attempted to) Push Notifications for my app. I have sorted all the certificates out and have everything running within Xcode. I uploaded my .p12 file to Firebase in the development section and even downloaded the provisioning profile and reinstalled it into my project.
This is the code in my AppDelegate.swift file
Updated code:
import UIKit
import Firebase
import FirebaseMessaging
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var storyboard: UIStoryboard?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
FIRApp.configure()
// Override point for customization after application launch.
self.storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let currentUser = FIRAuth.auth()?.currentUser
if currentUser != nil
{
self.window?.rootViewController = self.storyboard?.instantiateViewControllerWithIdentifier("tBVC")
}
else
{
self.window?.rootViewController = self.storyboard?.instantiateViewControllerWithIdentifier("loginScreen")
}
return true
}
func registerForPushNotifications(application: UIApplication) {
let notificationSettings = UIUserNotificationSettings(
forTypes: [.Badge, .Sound, .Alert], categories: nil)
application.registerUserNotificationSettings(notificationSettings)
}
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
if notificationSettings.types != .None {
application.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 throttle down OpenGL ES frame rates. 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 inactive 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(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
print(userInfo)
print("MessageID: \(userInfo["gcm_message_id"]!)")
//
}
}
When the app is running in the background no notifications display, even when my device is locked still nothing. The alert popped up asking if the app had permission to send notifications and I said yes.
I followed this tutorial
Any idea why my notifications aren't being displayed?
In the Firebase Console it says that the status of the notification is 'Completed'
EDIT - Added image of my capabilities in Xcode
I worked out the reason for why it was doing so! As #Collinizer stated there were issues with Apple and there APNS but it is all working now! I added push notifications in using OneSignal and they are working like a dream!
Thank you to all that helped :)
You need to configure set up of APNS device token which is crucial to push notifications with Firebase Cloud Messaging (FCM).
First let's back up a little bit and start by just seeing if we can at least get token success.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
FIRApp.configure()
return true
}
func registerForPushNotifications(application: UIApplication) {
let notificationSettings = UIUserNotificationSettings(
forTypes: [.Badge, .Sound, .Alert], categories: nil)
application.registerUserNotificationSettings(notificationSettings)
}
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
if notificationSettings.types != .None {
application.registerForRemoteNotifications()
}
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
var tokenString = ""
for i in 0..<deviceToken.length {
tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
}
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Unknown)
print("Device Token:", tokenString)
}