I am using Swift 3.0 and I want the user to be able to click on a button to trigger the alert box that requests his permission for using notifications.
I am surprised not to find more information about that.
I would like to support iOS 9.0 as well as 10.
What is the way to trigger this ask-for-permission alert box again ?
import UserNotifications
and Declare this UNUserNotificationCenterDelegate Method in header
in appDelegates just put this code :
func registerForRemoteNotification() {
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
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()
}
}
And when user give permission at that time you can get user token via didRegisterForRemoteNotificationsWithDeviceToken Delegates method
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
print(token)
print(deviceToken.description)
if let uuid = UIDevice.current.identifierForVendor?.uuidString {
print(uuid)
}
UserDefaults.standard.setValue(token, forKey: "ApplicationIdentifier")
UserDefaults.standard.synchronize()
}
Below is the full code for all the scenarios, check with break points
Working copy of code, copy paste in your Appdelegate.
XCode 9 , iOS 11, Swift 4
//
// AppDelegate.swift
// PushNotification
import UIKit
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 10, *)
{ // iOS 10 support
//create the notificationCenter
let center = UNUserNotificationCenter.current()
center.delegate = self
// set the type as sound or badge
center.requestAuthorization(options: [.sound,.alert,.badge]) { (granted, error) in
if granted {
print("Notification Enable Successfully")
}else{
print("Some Error Occure")
}
}
application.registerForRemoteNotifications()
}
else if #available(iOS 9, *)
{
// iOS 9 support
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
else if #available(iOS 8, *)
{
// iOS 8 support
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound,
.alert], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
else
{ // iOS 7 support
application.registerForRemoteNotifications(matching: [.badge, .sound, .alert])
}
return true
}
//get device token here
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken
deviceToken: Data)
{
var token = ""
for i in 0..<deviceToken.count {
token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
}
print("Registration succeeded!")
print("Token: ", token)
//send tokens to backend server
// storeTokens(token)
}
//get error here
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error:
Error) {
print("Registration failed!")
}
//get Notification Here below ios 10
func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {
// Print notification payload data
print("Push notification received: \(data)")
}
//This is the two delegate method to get the notification in iOS 10..
//First for foreground
#available(iOS 10.0, *)
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)")
}
//Second for background and close
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response:UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void)
{
print("Handle push from background or closed")
// if you set a member variable in didReceiveRemoteNotification, you will know if this is from closed or background
print("\(response.notification.request.content.userInfo)")
}
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:.
}
}
You can use UserNotifications framework to handle notifications for iOS app. Once you ask for authorization system will automatically prompts alert to user.
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (success, error) in
if let error = error {
print("Request Authorization Failed (\(error), \(error.localizedDescription))")
}
else{
//Success.. do something on success
}
}
For iOS 9.0 :
private func requestAuthorizationForiOS9AndBelow(){
let notificationSettings = UIUserNotificationSettings(
types: [.badge, .sound, .alert], categories: nil)
UIApplication.shared.registerUserNotificationSettings(notificationSettings)
}
You can do this way
In AppDelegate inside the didFinishLaunching method
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: { (granted, error) in
if (granted == true){
}else{
print("request authorisation error: \(error)")
}
})
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
Related
In old projects I have receiving the device token when app install first time or refresh the token. But now I create a new project and write code for did register device token delegate and ask permission but now did register device token is not called in swift version 4.2 . Has anyone faced this issue? If yes, what is solution?
import UIKit
import FirebaseInstanceID
import GoogleMaps
import GooglePlaces
import UserNotifications
import FirebaseCore
import FirebaseMessaging
import Alamofire
import Fabric
import Crashlytics
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate,MessagingDelegate,CLLocationManagerDelegate {
var window: UIWindow?
let locationManager = CLLocationManager()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if let statusbar = UIApplication.shared.value(forKey: "statusBar") as? UIView {
statusbar.backgroundColor = UIColor.fromHexaString(hex: "feac1c")
}
UIApplication.shared.statusBarStyle = .lightContent
Fabric.with([Crashlytics.self])
let remoteNotif = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] as? NSDictionary
if remoteNotif != nil
{
}
else
{
print("Not remote")
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
}
GMSServices.provideAPIKey(google_url_links().google_mapKey)
GMSPlacesClient.provideAPIKey(google_url_links().google_mapKey)
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
Messaging.messaging().delegate = self
})
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
FirebaseApp.configure()
NotificationCenter.default.addObserver(self, selector: #selector(appDelegate.tokenRefereshNotification), name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)
// Override point for customization after application launch.
return true
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print(remoteMessage.appData)
}
// func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
//
// print("Firebase registration token: \(fcmToken)")
// UserDefaults.standard.set(fcmToken, forKey: "DeviceToken")
//
//
// }
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
Messaging.messaging().apnsToken = deviceToken
//FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: .none)
// Messaging.messaging().setAPNSToken(deviceToken, type: .sandbox)
}
#objc func tokenRefereshNotification()
{
let refereshtoken = InstanceID.instanceID().token() ?? ""
print("token23123::::\(refereshtoken)")
UserDefaults.standard.set(refereshtoken, forKey: "deviceToken")
connectToFCM()
}
func connectToFCM()
{
guard InstanceID.instanceID().token() != nil else
{
return
}
Messaging.messaging().disconnect()
Messaging.messaging().connect { (error) in
if (error != nil)
{
print("error unable to connect\(String(describing: error))")
}
else
{
print("connect to fcm")
}
}
}
#objc func CheckInterntConnection()
{
let alert = UIAlertController(title: "", message: custom_message().error_internet, preferredStyle: UIAlertController.Style.actionSheet)
alert.addAction(UIAlertAction(title: custom_message().OK, style: UIAlertAction.Style.default, handler: nil))
self.window?.rootViewController?.present(alert, animated: true, completion: nil)
}
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:.
}
}
You need to do this too get firebase Token
Declare a variable in your AppDelegate class.
var firebaseToken: String = ""
Call these methods in your didFinishLaunchingWithOptions function
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
self.registerForFirebaseNotification(application: application)
Messaging.messaging().delegate = self
return true
}
Add this function in your AppDelegate class.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
}
func registerForFirebaseNotification(application: UIApplication) {
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()
}
}
And Last create an extension of AppDelegate and add these functions
extension AppDelegate: MessagingDelegate, UNUserNotificationCenterDelegate {
//MessagingDelegate
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
self.firebaseToken = fcmToken
print("Firebase token: \(fcmToken)")
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("didReceive remoteMessage: \(remoteMessage)")
}
//UNUserNotificationCenterDelegate
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print("APNs received with: \(userInfo)")
}
}
The same methods in swift will help you to trace token delegate data
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(#"Unable to register for remote notifications: %#", error);
}
// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the
//APNs device token can be paired to
// the FCM registration token.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(#"APNs device token retrieved: %#", deviceToken);
// With swizzling disabled you must set the APNs device token here.
[FIRMessaging messaging].APNSToken = deviceToken;
}
You have to call the following function to get fcm token,
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
UserDefaults.standard.set(fcmToken, forKey: "DeviceToken")
}
and edit your didFinishLaunchingWithOptions() of appDelegate as,
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
if(launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] != nil){
}
InstanceID.instanceID().instanceID { (result, error) in
if let error = error {
print("Error fetching remote instance ID: \(error)")
} else if let result = result {
print("Remote instance ID token: \(result.token)")
}
}
Messaging.messaging().isAutoInitEnabled = true
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert,.sound] // .badge,
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert,.sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
Messaging.messaging().delegate = self
return true
}
Messaging.messaging().token { token, tokenGenerationError in
if let token = token{
print("the token is \(token)")
}
if let tokenError = tokenGenerationError{
print("the tokenError is \(tokenError)")
}
}
You just code these lines in didFinishLaunchingWithOptions and then run then you can see the Token in print console and use that token in Firebase.
Here is my AppDelegate (made from a developer in Xcode 8.3, iOS10), it is working perfectly to send notifications, but I would like to add a badge to my iPhone dashboard.
I tried to add application.applicationBadgeNumber = XX but the XX never updates, it stays on XX no matter if there are 5 new notifications or none (which should delete the badge at this point).
How can I make badge icon flows correctly to show if there is a new notification or not in the app?
import UIKit
import Firebase
import IQKeyboardManagerSwift
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// UINavigationBar.appearance().barTintColor = UIColor.black
UINavigationBar.appearance().tintColor = UIColor(red:0.00, green:0.81, blue:1.00, alpha:1.0)
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor(red:0.00, green:0.81, blue:1.00, alpha:1.0)]//[NSForegroundColorAttributeName:UIColor.white]
/*
let navBackgroundImage:UIImage! = UIImage(named: "background.png")
UINavigationBar.appearance().setBackgroundImage(navBackgroundImage, for: .default)
UINavigationBar.appearance().tintColor = UIColor.black
*/
UITabBar.appearance().tintColor = UIColor(red:0.00, green:0.81, blue:1.00, alpha:1.0)
UITabBar.appearance().barTintColor = UIColor(red:0.98, green:0.98, blue:0.98, alpha:1.0)
FIRApp.configure()
IQKeyboardManager.sharedManager().enable = true
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()
NotificationCenter.default.addObserver(self,
selector: #selector(self.tokenRefreshNotification),
name: .firInstanceIDTokenRefresh,
object: nil)
let storyboard = self.grabStoryboard()
// display storyboard
self.window!.rootViewController! = storyboard.instantiateInitialViewController()!
self.window!.makeKeyAndVisible()
return true
}
func grabStoryboard() -> UIStoryboard {
// determine screen size
let screenHeight = UIScreen.main.bounds.size.height
print ("screen : \(screenHeight)")
var storyboard: UIStoryboard?
switch screenHeight {
// iPhone 4s
case 480:
print("ici iphone4")
storyboard = UIStoryboard(name: "iphone4", bundle: nil)
// iPhone 5s
default:
// it's an iPad
print("ici default")
storyboard = UIStoryboard(name: "Main", bundle: nil)
}
return storyboard!
}
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()
print("Disconnected from FCM.")
}
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 application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: .un)
// FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: .unknown)
let chars = (deviceToken as NSData).bytes.bindMemory(to: CChar.self, capacity: deviceToken.count)
var token = ""
for i in 0..<deviceToken.count {
token += String(format: "%02.2hhx", arguments: [chars[i]])
}
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.unknown)
print("Device Token = ", token)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Did Fail to Register for Remote Notifications")
print("\(error), \(error.localizedDescription)")
}
func tokenRefreshNotification(_ notification: Notification) {
if let refreshedToken = FIRInstanceID.instanceID().token() {
// constantsApp.user.deviceToken = refreshedToken
print("InstanceID token: \(refreshedToken)")
}
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
}
func connectToFcm() {
FIRMessaging.messaging().connect { (error) in
if (error != nil) {
print("Unable to connect with FCM. \(error ?? "" as! Error)")
} else {
print("Connected to FCM.")
}
}
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// [START receive_message]
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.
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
// [END receive_message]
}
#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)
}
#available(iOS 10, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
print("Userinfo \(response.notification.request.content.userInfo)")
// print("Userinfo \(response.notification.request.content.userInfo)")
}
}
extension AppDelegate : FIRMessagingDelegate {
// Receive data message on iOS 10 devices.
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
print("%#", remoteMessage.appData)
}
}
For iOS 10:
You need to implement UserNotifications into your AppDelegate.
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
if error != nil {
//
}
}
return true
}
Then you can do:
let content = UNMutableNotificationContent()
content.badge = 10 // your badge count
For older iOS:
let badgeCount: Int = 123
let application = UIApplication.sharedApplication()
if #available(iOS 7.0, *) {
application.applicationIconBadgeNumber = badgeCount
}
if #available(iOS 8.0, *) {
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Badge], categories: nil))
application.applicationIconBadgeNumber = badgeCount
}
if #available(iOS 9.0, *) {
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Badge], categories: nil))
application.applicationIconBadgeNumber = badgeCount
}
I've been breaking my head on this today and yesterday, for some reason my iOS application is not receiving any firebase notifications. For as far as I know I have done everything as it should be.
I have checked the certifications in my Apple developer account and everything is set up correctly (see screenshots).
I am testing on a physical device
Firebase is set up properly and the logs show it connected to firebase correctly
I have enabled push notifications, background fetch and remote notifications in the capabilities tab of the project
I have added my APN key from my Apple console to Firebase
When sending a notification through the Firebase console to a topic or to all iOS apps nothing happens. I have the same app running on android smoothly which is receiving all notifications when targeted.
AppDelegate.swift
//
// AppDelegate.swift
// CoyoteBreda
//
// Created by Milan van Dijck on 28/02/2017.
// Copyright © 2017 Miscoria web development. All rights reserved.
//
import UIKit
import GoogleMaps
import Firebase
import FirebaseMessaging
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
GMSServices.provideAPIKey("AIzaSyB2JNmY2D6q7lYKmJmyeeDXdk-ILEM4q1Q")
UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
//Initialize firebase
//FIRApp.configure()
do {
Network.reachability = try Reachability(hostname: "www.google.com")
do {
try Network.reachability?.start()
} catch let error as Network.Error {
print(error)
} catch {
print(error)
}
} catch {
print(error)
}
// Add observer for InstanceID token refresh callback.
NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification),
name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)
return true
}
func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
// -----------------------
// FIREBASE MESSAGING
// -----------------------
FIRApp.configure()
application.registerForRemoteNotifications()
requestNotificationAuthorization(application: application)
if let userInfo = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] {
NSLog("[RemoteNotification] applicationState: \(applicationStateString) didFinishLaunchingWithOptions for iOS9: \(userInfo)")
//TODO: Handle background notification
}
application.registerForRemoteNotifications()
return true;
}
func tokenRefreshNotification(notification: NSNotification)
{
if let refreshedToken = FIRInstanceID.instanceID().token()
{
print("InstanceID token: \(refreshedToken)")
}
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData)
{
FIRInstanceID.instanceID().setAPNSToken(deviceToken as Data, type: FIRInstanceIDAPNSTokenType.sandbox)
FIRInstanceID.instanceID().setAPNSToken(deviceToken as Data, type: FIRInstanceIDAPNSTokenType.prod)
}
func connectToFcm()
{
FIRMessaging.messaging().connect { (error) in
if (error != nil)
{
print("[Unable to connect with FCM. \(String(describing: error))]")
}
else
{
print("[Connected to FCM.]")
}
}
}
var applicationStateString: String {
if UIApplication.shared.applicationState == .active {
return "active"
} else if UIApplication.shared.applicationState == .background {
return "background"
}else {
return "inactive"
}
}
func requestNotificationAuthorization(application: UIApplication) {
if #available(iOS 10.0, *) {
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)
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("[REGISTERING FOR TOPICS]")
FIRMessaging.messaging().subscribe(toTopic: "/topics/activiteit")
FIRMessaging.messaging().subscribe(toTopic: "/topics/message")
}
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
// Update the database
DatabaseUpdater.performUpdate(performFetchWithCompletionHandler: completionHandler)
// TODO: update views
//completionHandler(.newData)
}
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.
connectToFcm()
DatabaseUpdater.performUpdate(performFetchWithCompletionHandler: {(result: UIBackgroundFetchResult) -> Void in
NSLog("Done updating!")
})
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
#available(iOS 10, *)
extension AppDelegate : FIRMessagingDelegate {
// Receive data message on iOS 10 devices.
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
print("%#", remoteMessage.appData)
}
}
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
NSLog("[UserNotificationCenter] applicationState: \(applicationStateString) 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
NSLog("[UserNotificationCenter] applicationState: \(applicationStateString) didReceiveResponse: \(userInfo)")
//TODO: Handle background notification
completionHandler()
}
}
Application output:
Apple certificates:
Any help would be much appreciated.
try this
import UIKit
import Firebase
import FirebaseMessaging
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder,UIApplicationDelegate,UNUserNotificationCenterDelegate{
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
//create the notificationCenter
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)
//FIRMessaging.messaging().remoteMessageDelegate = self
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
FirebaseApp.configure()
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
var token = ""
for i in 0..<deviceToken.count {
token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
}
print("Registration succeeded! Token: ", token)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Registration failed!")
}
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:.
}
// Firebase notification received
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (_ options: UNNotificationPresentationOptions) -> Void) {
// custom code to handle push while app is in the foreground
print("Handle push from foreground\(notification.request.content.userInfo)")
// let dict = notification.request.content.userInfo["aps"] as! NSDictionary
// print(dict)
// let d : [String : Any] = dict["alert"] as! [String : Any]
// let body : String = d["body"] as! String
// let title : String = d["title"] as! String
//
// print("Title:\(title) + body:\(body)")
//
//
//
// self.showAlertAppDelegate(title: title,message:body,buttonTitle:"ok",window:self.window!)
completionHandler(.alert)
}
#available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
// if you set a member variable in didReceiveRemoteNotification, you will know if this is from closed or background
if response.actionIdentifier == "goToApp"{
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = nextViewController
}else if response.actionIdentifier == "cancel" {
print("close")
}else {
}
print("Handle push from background or closed\(response.notification.request.content.userInfo)")
}
func showAlertAppDelegate(title: String,message : String,buttonTitle: String,window: UIWindow){
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: buttonTitle, style: UIAlertActionStyle.default, handler: nil))
window.rootViewController?.present(alert, animated: false, completion: nil)
}
// Firebase ended here
}
As you say that you are receiving notification in Android and having issue with iOS, then there is possibility that this issue comes because of Payload format. I also met with this issue earlier.
Please make sure that your Payload format must be like below.
{
"aps" : {
"alert" : {
"body" : "great match!",
"title" : "Portugal vs. Denmark",
},
"badge" : 1,
},
"customKey" : "customValue"
}
And if your app running on ios 10 or later, then make sure you set delegate.
For more information, see here
I have been trying to get firebase push-notification in my ios app for a long time. I have tried everything on the internet I could find. But sadly no luck.
Any help would be appreciated.
I am sending notification through firebase console. And sometimes when the app is running on foreground the last part
extension AppDelegate : FIRMessagingDelegate {
// Receive data message on iOS 10 devices.
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
print("noti recieve remote notification in extesnion")
print("%# debug", remoteMessage)
print("%#", remoteMessage.appData)
}
gets called, but nothing happens when the app is in background. I have enabled "Push Notification" and Background Modes" in capabilities.
I have tested this only in a ios 10 device.
Here is my code in AppDelegate.swift
import UIKit
import FirebaseMessaging
import Firebase
import UserNotifications
import FirebaseInstanceID
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FIRApp.configure()
/* let notificationType : UIUserNotificationType = [UIUserNotificationType.alert, UIUserNotificationType.badge, UIUserNotificationType.sound]
let notificationSettings: UIUserNotificationSettings = UIUserNotificationSettings(types:notificationType,categories:nil)
application.registerForRemoteNotifications()
application.registerUserNotificationSettings(notificationSettings)*/
if #available(iOS 10.0, *) {
print("if ios 10 ")
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
application.registerForRemoteNotifications()
} else {
print("noti not ios 10")
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
// [END register_for_notifications]
// Add observer for InstanceID token refresh callback.
NotificationCenter.default.addObserver(self,
selector: #selector(self.tokenRefreshNotification),
name: NSNotification.Name.firInstanceIDTokenRefresh,
object: nil)
return true }
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("noti didRegister notification woth device tocken")
/* let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
var tokenString = ""
for i in 0..<deviceToken.count {
tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
}*/
/* var token: String = ""
for i in 0..<deviceToken.count {
token += String(format: "%02.2hhx", deviceToken[i] as CVarArg)
}
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.prod)
print("noti tokenString: \(token)")*/
}
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:.
}
// [START receive_message]
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
print("noti notification recieved")
// 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
// Print message ID.
// print("Message ID: \(userInfo["gcm.message_id"]!)")
print("%#", "noti didReceiveRemoteNotification log")
// Print full message.
print("%#", userInfo)
}
// [END receive_message]
// [START refresh_token]
func tokenRefreshNotification(notification: NSNotification) {
print("noti refresh tocken")
if let refreshedToken = FIRInstanceID.instanceID().token() {
print("noti InstanceID token: \(refreshedToken)")
}
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
}
// [END refresh_token]
// [START connect_to_fcm]
func connectToFcm() {
FIRMessaging.messaging().connect { (error) in
if (error != nil) {
print("noti Unable to connect with FCM. \(error)")
} else {
print("noti Connected to FCM.")
}
}
}
// [END connect_to_fcm]
func applicationDidBecomeActive(application: UIApplication) {
connectToFcm()
}
// [START disconnect_from_fcm]
func applicationDidEnterBackground(application: UIApplication) {
FIRMessaging.messaging().disconnect()
print("noti Disconnected from FCM.")
}
// [END disconnect_from_fcm]
}
// [START ios_10_message_handling]
#available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(center: UNUserNotificationCenter,
willPresentNotification notification: UNNotification,
withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
print("noti userNotificationCenter #ios10")
let userInfo = notification.request.content.userInfo
// Print message ID.
print("Message ID: \(userInfo["gcm.message_id"]!)")
// Print full message.
print("%#", userInfo)
}
}
extension AppDelegate : FIRMessagingDelegate {
// Receive data message on iOS 10 devices.
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
print("noti recieve remote notification in extesnion")
print("%# debug", remoteMessage)
print("%#", remoteMessage.appData)
}
}
I solved the problem by adding the code below to the project.
FIRInstanceIDAPNSTokenType.Sandbox will be used when you install the app though TestFlight,
and FIRInstanceIDAPNSTokenType.Prod when your app goes live on the App Store.
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData)
{
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type:FIRInstanceIDAPNSTokenType.Sandbox)
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type:FIRInstanceIDAPNSTokenType.Prod)
}
Try this. This is working.
import UIKit
import Firebase
import UserNotifications
import FirebaseInstanceID
import FirebaseMessaging
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
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()
NotificationCenter.default.addObserver(self,
selector: #selector(self.tokenRefreshNotification),
name: .firInstanceIDTokenRefresh,
object: nil)
FIRApp.configure()
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()
print("Disconnected from FCM.")
}
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:.
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let chars = (deviceToken as NSData).bytes.bindMemory(to: CChar.self, capacity: deviceToken.count)
var token = ""
for i in 0..<deviceToken.count {
token += String(format: "%02.2hhx", arguments: [chars[i]])
}
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.unknown)
print("Device Token = ", token)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Did Fail to Register for Remote Notifications")
print("\(error), \(error.localizedDescription)")
}
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
// Print message ID.
print("Message ID: \(userInfo["gcm.message_id"]!)")
// Print full message.
print("%#", userInfo)
}
// [START refresh_token]
func tokenRefreshNotification(_ notification: Notification) {
if let refreshedToken = FIRInstanceID.instanceID().token() {
print("InstanceID token: \(refreshedToken)")
}
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
}
// [END refresh_token]
func connectToFcm() {
FIRMessaging.messaging().connect { (error) in
if (error != nil) {
print("Unable to connect with FCM. \(error)")
} else {
print("Connected to FCM.")
}
}
}
}
#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)
}
#available(iOS 10, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
print("Userinfo \(response.notification.request.content.userInfo)")
// print("Userinfo \(response.notification.request.content.userInfo)")
}
}
extension AppDelegate : FIRMessagingDelegate {
// Receive data message on iOS 10 devices.
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
print("%#", remoteMessage.appData)
}
}
Surprisingly, all I did to fix the problem, was actually deleting and reinstalling the app. Hope that helps.
Thank you for asking this question.
It is compulsory to use below statement while you have comment this line in code
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.prod)
Uncomment below code...
Hope it will help you...
I'm trying to get my app working in Xcode 8.0, and am running into an error. I know this code worked fine in previous versions of swift, but I'm assuming the code for this is changed in the new version. Here's the code I'm trying to run:
let settings = UIUserNotificationSettings(forTypes: [.Sound, .Alert, .Badge], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.shared().registerForRemoteNotifications()
The error that I'm getting is "Argument labels '(forTypes:, categories:)' do not match any available overloads"
Is there a different command that I could try to get this working?
Import the UserNotifications framework and add the UNUserNotificationCenterDelegate in AppDelegate.swift
Request user permission
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
application.registerForRemoteNotifications()
return true
}
Getting device token
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print(deviceTokenString)
}
In case of error
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("i am not available in simulator \(error)")
}
In case if you need to know the permissions granted
UNUserNotificationCenter.current().getNotificationSettings(){ (settings) in
switch settings.soundSetting{
case .enabled:
print("enabled sound setting")
case .disabled:
print("setting has been disabled")
case .notSupported:
print("something vital went wrong here")
}
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if #available(iOS 10, *) {
//Notifications get posted to the function (delegate): func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void)"
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
guard error == nil else {
//Display Error.. Handle Error.. etc..
return
}
if granted {
//Do stuff here..
//Register for RemoteNotifications. Your Remote Notifications can display alerts now :)
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
}
else {
//Handle user denying permissions..
}
}
//Register for remote notifications.. If permission above is NOT granted, all notifications are delivered silently to AppDelegate.
application.registerForRemoteNotifications()
}
else {
let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
return true
}
import UserNotifications
Next, go to the project editor for your target, and in the General tab, look for the Linked Frameworks and Libraries section.
Click + and select UserNotifications.framework:
// iOS 12 support
if #available(iOS 12, *) {
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound, .provisional, .providesAppNotificationSettings, .criticalAlert]){ (granted, error) in }
application.registerForRemoteNotifications()
}
// iOS 10 support
if #available(iOS 10, *) {
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
application.registerForRemoteNotifications()
}
// iOS 9 support
else if #available(iOS 9, *) {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
// iOS 8 support
else if #available(iOS 8, *) {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
// iOS 7 support
else {
application.registerForRemoteNotifications(matching: [.badge, .sound, .alert])
}
Use Notification delegate methods
// 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("APNs device token: \(deviceTokenString)")
}
// 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)")
}
For receiving push notification
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
completionHandler(UIBackgroundFetchResult.noData)
}
Setting up push notifications is enabling the feature within Xcode 8
for your app. Simply go to the project editor for your target and then
click on the Capabilities tab. Look for Push Notifications and toggle
its value to ON.
Check below link for more Notification delegate methods
Handling Local and Remote Notifications UIApplicationDelegate - Handling Local and Remote Notifications
https://developer.apple.com/reference/uikit/uiapplicationdelegate
I had issues with the answers here in converting the deviceToken Data object to a string to send to my server with the current beta of Xcode 8. Especially the one that was using deviceToken.description as in 8.0b6 that would return "32 Bytes" which isn't very useful :)
This is what worked for me...
Create an extension on Data to implement a "hexString" method:
extension Data {
func hexString() -> String {
return self.reduce("") { string, byte in
string + String(format: "%02X", byte)
}
}
}
And then use that when you receive the callback from registering for remote notifications:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = deviceToken.hexString()
// Send to your server here...
}
In iOS10 instead of your code, you should request an authorization for notification with the following: (Don't forget to add the UserNotifications Framework)
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().requestAuthorization([.alert, .sound, .badge]) { (granted: Bool, error: NSError?) in
// Do something here
}
}
Also, the correct code for you is (use in the else of the previous condition, for example):
let setting = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
UIApplication.shared().registerUserNotificationSettings(setting)
UIApplication.shared().registerForRemoteNotifications()
Finally, make sure Push Notification is activated under target-> Capabilities -> Push notification. (set it on On)
Well this work for me.
First in AppDelegate
import UserNotifications
Then:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
registerForRemoteNotification()
return true
}
func registerForRemoteNotification() {
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()
}
}
To get devicetoken:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
}
Heads up, you should be using the main thread for this action.
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
if granted {
DispatchQueue.main.async(execute: {
UIApplication.shared.registerForRemoteNotifications()
})
}
}
First, listen to user notification status, i.e., registerForRemoteNotifications() to get APNs device token;
Second, request authorization. When being authorized by the user, deviceToken will be sent to the listener, the AppDelegate;
Third, report the device token to your server.
extension AppDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// 1. listen(监听) to deviceToken
UIApplication.shared.registerForRemoteNotifications()
// 2. request device token
requestAuthorization()
}
func requestAuthorization() {
if #available(iOS 10, *) {
let uc = UNUserNotificationCenter.current()
uc.delegate = UIApplication.shared.delegate as? AppDelegate
uc.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if let error = error { // 无论是拒绝推送,还是不提供 aps-certificate,此 error 始终为 nil
print("UNUserNotificationCenter 注册通知失败, \(error)")
}
DispatchQueue.main.async {
onAuthorization(granted: granted)
}
}
} else {
let app = UIApplication.shared
app.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
}
}
// 在 app.registerUserNotificationSettings() 之后收到用户接受或拒绝及默拒后,此委托方法被调用
func application(_ app: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
// 已申请推送权限,所作的检测才有效
// a 征询推送许可时,用户把app切到后台,就等价于默拒了推送
// b 在系统设置里打开推送,但关掉所有形式的提醒,等价于拒绝推送,得不token,也收不推送
// c 关掉badge, alert和sound 时,notificationSettings.types.rawValue 等于 0 和 app.isRegisteredForRemoteNotifications 成立,但能得到token,也能收到推送(锁屏和通知中心也能看到推送),这说明types涵盖并不全面
// 对于模拟器来说,由于不能接收推送,所以 isRegisteredForRemoteNotifications 始终为 false
onAuthorization(granted: app.isRegisteredForRemoteNotifications)
}
static func onAuthorization(granted: Bool) {
guard granted else { return }
// do something
}
}
extension AppDelegate {
func application(_ app: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
//
}
// 模拟器得不到 token,没配置 aps-certificate 的项目也得不到 token,网络原因也可能导致得不到 token
func application(_ app: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
//
}
}
The answer from ast1 is very simple and useful. It works for me, thank you so much.
I just want to poin it out here, so people who need this answer can find it easily. So, here is my code from registering local and remote (push) notification.
//1. In Appdelegate: didFinishLaunchingWithOptions add these line of codes
let mynotif = UNUserNotificationCenter.current()
mynotif.requestAuthorization(options: [.alert, .sound, .badge]) {(granted, error) in }//register and ask user's permission for local notification
//2. Add these functions at the bottom of your AppDelegate before the last "}"
func application(_ application: UIApplication, didRegister notificationSettings: UNNotificationSettings) {
application.registerForRemoteNotifications()//register for push notif after users granted their permission for showing notification
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("Device Token: \(tokenString)")//print device token in debugger console
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register: \(error)")//print error in debugger console
}
Simply do the following in didFinishWithLaunching::
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: []) { _, _ in
application.registerForRemoteNotifications()
}
}
Remember about import statement:
import UserNotifications
Take a look at this commented code:
import Foundation
import UserNotifications
import ObjectMapper
class AppDelegate{
let center = UNUserNotificationCenter.current()
}
extension AppDelegate {
struct Keys {
static let deviceToken = "deviceToken"
}
// MARK: - UIApplicationDelegate Methods
func application(_: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
if let tokenData: String = String(data: deviceToken, encoding: String.Encoding.utf8) {
debugPrint("Device Push Token \(tokenData)")
}
// Prepare the Device Token for Registration (remove spaces and < >)
setDeviceToken(deviceToken)
}
func application(_: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
debugPrint(error.localizedDescription)
}
// MARK: - Private Methods
/**
Register remote notification to send notifications
*/
func registerRemoteNotification() {
center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
// Enable or disable features based on authorization.
if granted == true {
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
} else {
debugPrint("User denied the permissions")
}
}
}
/**
Deregister remote notification
*/
func deregisterRemoteNotification() {
UIApplication.shared.unregisterForRemoteNotifications()
}
func setDeviceToken(_ token: Data) {
let token = token.map { String(format: "%02.2hhx", arguments: [$0]) }.joined()
UserDefaults.setObject(token as AnyObject?, forKey: “deviceToken”)
}
class func deviceToken() -> String {
let deviceToken: String? = UserDefaults.objectForKey(“deviceToken”) as? String
if isObjectInitialized(deviceToken as AnyObject?) {
return deviceToken!
}
return "123"
}
func isObjectInitialized(_ value: AnyObject?) -> Bool {
guard let _ = value else {
return false
}
return true
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping(UNNotificationPresentationOptions) -> Swift.Void) {
("\(notification.request.content.userInfo) Identifier: \(notification.request.identifier)")
completionHandler([.alert, .badge, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping() -> Swift.Void) {
debugPrint("\(response.notification.request.content.userInfo) Identifier: \(response.notification.request.identifier)")
}
}
Let me know if there is any problem!