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

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.

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])
}
}
}

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[FBLPromise HTTPBody]

I m building a swift application. I m trying to integrate Firebase Notification message. So I write all code as documentation, but if I try to start application after some seconds, I will have this strange error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[FBLPromise HTTPBody]: unrecognized selector sent to instance 0x281b9cdb0'
This is my CocoaPods file:
target 'appUser' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
pod 'TPKeyboardAvoidingSwift'
pod 'ActiveLabel'
pod 'HSAttachmentPicker'
pod 'IQKeyboardManagerSwift'
pod 'Alamofire', '~> 4.8.0'
pod 'SwiftyJSON'
pod 'DropDown'
pod 'SDWebImage/WebP'
pod 'SVProgressHUD'
pod 'Cosmos'
pod 'Gallery'
pod 'Charts'
pod 'Firebase/Analytics'
pod 'Firebase/Messaging'
# Pods for appUser
#target 'appUserTests' do
# inherit! :search_paths
# Pods for testing
#end
#target 'appUserUITests' do
# Pods for testing
#end
end
This is the code into AppDelegate.swift file
//
import UIKit
import Firebase
import FirebaseMessaging
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,MessagingDelegate {
var window: UIWindow?
let notificationCenter = UNUserNotificationCenter.current()
/*func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}*/
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions:
[UIApplication.LaunchOptionsKey: Any]?) -> Bool {
USER_DEFAULT.set("mykey", forKey: IOS_TOKEN)
notificationCenter.delegate = self
FirebaseApp.configure()
Messaging.messaging().delegate = self
Messaging.messaging().isAutoInitEnabled = true
self.configureNotification()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func configureNotification() {
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
}
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
Messaging.messaging().token { token, error in
if let error = error {
print("Error fetching FCM registration token: \(error)")
} else if let token = token {
print("FCM registration token: \(token)")
USER_DEFAULT.set(token, forKey: IOS_TOKEN)
}
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
// k.iosRegisterId = deviceTokenString
Messaging.messaging().apnsToken = deviceToken
print("APNs device token: \(deviceTokenString)")
// USER_DEFAULT.set(deviceTokenString, forKey: IOS_TOKEN)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("APNs registration failed: \(error)")
}
// MARK:-  Received Remote Notification
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
Messaging.messaging().appDidReceiveMessage(userInfo)
print("main method - \(userInfo)")
if let info = userInfo as? Dictionary<String, AnyObject> {
//let alert1 = info["aps"]!["alert"] as! Dictionary<String, AnyObject>
let title = userInfo["gcm.notification.status"] as! String
hanleNotification(info: info, strStatus: title, strFrom: "Front")
}
completionHandler(UIBackgroundFetchResult.newData)
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
print("willPresent \(userInfo)")
Messaging.messaging().appDidReceiveMessage(userInfo)
/*if let info = userInfo as? Dictionary<String, AnyObject> {
let title = userInfo["google.c.a.c_l"] as! String
hanleNotification(info: info, strStatus: title, strFrom: "Front")
}*/
completionHandler([[.alert, .sound]])
}
//metodo chiamata quando l'utente clicca sulla notifica
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
print("Did Recceive \(userInfo)")
if let info = userInfo as? Dictionary<String, AnyObject> {
//let alert1 = info["aps"]!["alert"] as! Dictionary<String, AnyObject>
//let title = userInfo["gcm.notification.data"]
hanleNotification(info: info, strStatus: "titolo", strFrom: "Back")
}
//Messaging.messaging().appDidReceiveMessage(userInfo)
completionHandler()
}
/*func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
Messaging.messaging().appDidReceiveMessage(userInfo)
completionHandler(.noData)
}*/
//MARK:GoViewCotroller
func hanleNotification(info:Dictionary<String,AnyObject>,strStatus:String,strFrom:String) {
let visibleVC = UIApplication.topViewController()
//recupero i dati del messaggio
var datiNascosti = info["gcm.notification.data"]
//let swiftyJsonVar = JSON(datiNascosti)
datiNascosti = datiNascosti?.replacingOccurrences(of: "\"", with: "") as AnyObject
datiNascosti = datiNascosti?.replacingOccurrences(of: "{", with: "") as AnyObject
datiNascosti = datiNascosti?.replacingOccurrences(of: "}", with: "") as AnyObject
let array:[String]? = datiNascosti?.components(separatedBy: [","])
var contentOfPushMessage = [String: String]()
for riga in array! {
//ho ogni riga adesso effettuo lo split
let rigaSlittata:[String]? = riga.components(separatedBy: [":"])
if(rigaSlittata!.count > 1){
contentOfPushMessage[rigaSlittata![0]] = rigaSlittata![1]
}
}
print("ho creato il mio dizionario con i dati ottenuti")
//se nel dizionario esiste la chiave status ed il valore = chat
//devo aprire direttamente la chat con l'utente
if contentOfPushMessage.keys.contains("status") {
// contains key
let status = contentOfPushMessage["status"]
if(status == "chat"){
//devo aprire la chat. Mi occorre anche l'id del utente
let user_id = contentOfPushMessage["user_id"]
let username = contentOfPushMessage["username"]
//apro il mio ViewController
guard let window = UIApplication.shared.keyWindow else { return }
//let storyboard = UIStoryboard(name: "YourStoryboard", bundle: nil)
let objVC = kStoryboardMain.instantiateViewController(withIdentifier: "ChatVC") as! ChatVC
objVC.receiverId = user_id!
objVC.userName = username!
let navController = UINavigationController(rootViewController: objVC)
navController.modalPresentationStyle = .fullScreen
// you can assign your vc directly or push it in navigation stack as follows:
window.rootViewController = navController
window.makeKeyAndVisible()
}
} else {
// does not contain key
}
if strStatus == "join_live_session" || strStatus == "exist_session" || strStatus == "join_request" {
// if visibleVC is liveSessionVC {
// NotificationCenter.default.post(name: NSNotification.Name(NotificationCenterStruct.JOIN_SESSION), object: "", userInfo: nil)
// } else {
// //visibleVC?.tabBarController?.selectedIndex = 2
// }
}
}
}
I attach also an image to display Xcode when app still crashed

having problem set up Firebase Cloud Messaging for ios App

I wanted to set up Firebase Cloud Messaging(FCM) for my iOS app. I followed the firebase documentation but I can't seem to get it to work. This is my app delegate file:
import UIKit
import Firebase
import FirebaseAnalytics
import FirebaseMessaging
#main
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
let gcmMessageIDKey = "gcmMessageIDKey"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
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()
Messaging.messaging().delegate = self
return true
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(String(describing: fcmToken))")
let dataDict:[String: String] = ["token": fcmToken ]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
// TODO: If necessary send token to application server.
// Note: This callback is fired at each app startup and whenever a new token is generated.
}
// 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
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// ...
// Print full message.
print(userInfo)
// Change this to your preferred presentation option
completionHandler([[.banner, .sound]])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// ...
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print full message.
print(userInfo)
completionHandler()
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
// 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.
}
}
I also set up the app capabilities:
capability setting
I also check many times that I have my APNs auth key right.
But when I tried to send a test notification from the firebase notification composer, nothing popped up on my phone. The function didReceiveRegistrationToken is working and provides a token, but when I used the token to 'send test message', nothing happened.
I tried to make an empty Xcode project side-by-side with the documentation to see if the issue is with my existing app, but it still didn't work.
Is there anything else that I'm missing here?

Using URLSession and background fetch together with remote notifications using firebase

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

Not receiving APNS messages from Azure after upgrade to Swift 3.0

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