Not receiving APNS messages from Azure after upgrade to Swift 3.0 - swift

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

Try to call this function on didFinishLaunchingWithOptions and clean >Run your app
func registerNotification()
{
UIApplication.sharedApplication()
let application = UIApplication.sharedApplication()
if application.respondsToSelector(#selector(UIApplication.registerUserNotificationSettings(_:)))
{
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
}
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
if notificationSettings.types != .None {
application.registerForRemoteNotifications()
}
}

Related

FCM Notifications are received in background but not foreground on iOS

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

Setting up firebase notifications

So I've been working on setting up firebase notifications using cloud messaging and I've run into a problem. I've been following this tutorial, so if I did anything else wrong, which hopefully I didn't, please let me know. I've also been looking at this one.
Here's my AppDelegate code, which is the spot in which they told me to put all the stuff. I also did the certificate stuff, and hopefully, that works fine:
import UIKit
import Firebase
import FirebaseMessaging
class AppDelegate: NSObject, UIApplicationDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions
launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
FirebaseApp.configure()
// 2
FirebaseConfiguration.shared.setLoggerLevel(.min)
UNUserNotificationCenter.current().delegate = self
// 2
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions) { _, _ in }
// 3
application.registerForRemoteNotifications()
Messaging.messaging().delegate = self //Here is one of the problems
return true
}
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler:
#escaping (UNNotificationPresentationOptions) -> Void
) {
completionHandler([[.banner, .sound]])
}
func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void
) {
completionHandler()
}
}
func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
Messaging.messaging().apnsToken = deviceToken //Here's the other problem
}
extension AppDelegate: MessagingDelegate {
func messaging(
_ messaging: Messaging,
didReceiveRegistrationToken fcmToken: String?
) {
let tokenDict = ["token": fcmToken ?? ""]
NotificationCenter.default.post(
name: Notification.Name("FCMToken"),
object: nil,
userInfo: tokenDict)
}
}
The problem:
Type 'Messaging' has no member 'messaging'
You might be using the old version of pods or dependencies.
FIRMessaging.messaging().delegate = self
Above code will work for you.
Alternative
If you are using pod you can updating with the following command.
pod update Firebase/Messaging
or just
pod update
Above command will update your all pods, be careful.
Yay. I found the solution. Pretty simple actually. I accidentally had a swift view in my app named Messaging which was throwing off the syntax.
If you're having this problem. Make sure nothing in your project is named Messaging.

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

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

Swift 3 - Local Notification's didReceiveRemoteNotification function not fired

I have managed to schedule a notification and show it to the user when the app is running/not running in the foreground. Now I need to display a ViewController upon the tap of this notification.
I understand that didReceiveRemoteNotification is the function that is called when the user taps on a notification. In my case, This function is never fired.
AppDelegate:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
return true
}
//didReceiveRemoteNotification goes here
The didReceiveRemoteNotification function:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
if ( application.applicationState == UIApplicationState.active)
{
print("Active")
// App is foreground and notification is recieved,
// Show a alert.
}
else if( application.applicationState == UIApplicationState.background)
{
print("Background")
// App is in background and notification is received,
// You can fetch required data here don't do anything with UI.
}
else if( application.applicationState == UIApplicationState.inactive)
{
print("Inactive")
// App came in foreground by used clicking on notification,
// Use userinfo for redirecting to specific view controller.
}
}
This is the entire Notification related code in my AppDelegate. Am I missing something?
For UserNotifications framework you need to work with UNUserNotificationCenterDelegate, so implement UNUserNotificationCenterDelegate with AppDelegate and set the delegate in didFinishLaunchingWithOptions method.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
return true
}
Now you need to implements userNotificationCenter(_:willPresent:withCompletionHandler:) and userNotificationCenter(_:didReceive:withCompletionHandler:) methods to get notification.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
//Handle notification
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
// pull out the buried userInfo dictionary
let userInfo = response.notification.request.content.userInfo
if let customData = userInfo["customData"] as? String {
print("Custom data received: \(customData)")
switch response.actionIdentifier {
case UNNotificationDefaultActionIdentifier:
// the user swiped to unlock
print("Default identifier")
case "show":
// the user tapped our "show more info…" button
print("Show more information…")
break
default:
break
}
}
// you must call the completion handler when you're done
completionHandler()
}
You can also check this AppCoda tutorial Introduction to User Notifications Framework in iOS 10 for more details.

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

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