I'm newbie to Swift, I am creating chat application, I need to send notification when app is in foreground or minimized.
But I am not getting the notification when app is minimized (it works when USB is connected.
Enabled Remote notification
Background Fetches in Xcode setup
Enabled Push Notification
Production APns certificate
Notification code:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
Messaging.messaging().delegate = self
Messaging.messaging().shouldEstablishDirectChannel = true
if #available(iOS 10.0, *) {
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, .badge], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
NotificationCenter.default.addObserver(self, selector: #selector(tokenRefreshNotification(_:)), name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)
return true
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
Messaging.messaging().appDidReceiveMessage(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
Messaging.messaging().appDidReceiveMessage(userInfo)
let action = userInfo["action"] as! String
let notification = UILocalNotification()
notification.fireDate = NSDate() as Date
notification.alertTitle = "test"
notification.alertBody = "test"
notification.alertAction = "Ok"
UIApplication.shared.applicationIconBadgeNumber = 1
UIApplication.shared.scheduleLocalNotification(notification)
completionHandler(UIBackgroundFetchResult.newData)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Unable to register for remote notifications: \(error.localizedDescription)")
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("APNs token retrieved: \(deviceToken)")
// With swizzling disabled you must set the APNs token here.
Messaging.messaging().apnsToken = deviceToken
}
}
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
completionHandler([.alert, .sound, .badge])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
print(userInfo)
completionHandler()
}
@objc func tokenRefreshNotification(_ notification: Notification) {
guard let token = InstanceID.instanceID().token() else {
print("No firebase token, aborting registering device")
return
}
print("No firebase token, aborting registering device")
}
}
extension AppDelegate : MessagingDelegate {
// [START refresh_token]
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
Messaging.messaging().subscribe(toTopic: "/topics/channel_18")
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Received data message: \(remoteMessage.appData)")
}
}
FCM Payload:
{
"to" : "/topics/channel_18",
"data" : {
"action" : "NOTIFY",
"message" : "{"text":"test" }"
},
"content_available" : true
}
I have tried with Priority high and with Sound option but none works.
Please note that I am not using "notification" key as per client request. i am using only data-message in FCM payload
Please anyone help me to work notification when app is in background without USB connection.
Apple does not offer a way to handle a notification that arrives when your app is closed (i.e. when the user has fully quit the application or the OS had decided to kill it while it is in the background). If this happens, the only way to handle the notification is to wait until it is opened by the user.
You have to put in the notification message title, icon, and content. You can send these messages using the Firebase console UI. In this way, a notification will be shown when the app is running in the background. Data Message: The app should handle these messages.
Go to Settings and tap Notifications. Select an app under Notification Style. Under Alerts, choose the alert style that you want. If you turn on Allow Notifications, choose when you want the notifications delivered — immediately or in the scheduled notification summary.
If it works with non-Silent notification then all it means is:
content_available
field into notification
(and since you don't want a title body then just don't add title/body) or just into the payload itself until see it working. default 13:11:47.178186 +0200 dasd DuetActivitySchedulerDaemon Removing a launch request for application <private> by activity <private> default com.apple.duetactivityscheduler
Then likely it's a bug similar to this iOS11 question. But you must open a new radar, because that radar was closed I believe because it was fixed!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With