Reload/refresh a scene after receive remote notification swiftUI - appdelegate

I have this problem. I'm receiving a notification from CloudKit using application:didReceiveRemoteNotification in AppDelegate. I'm able to receive the recordId, fetch it, and save it successfully. The problem is, the scene doesn't refresh.
final class UserData: ObservableObject {
#Published var items: [Item] = []
func saveFetchedItem(recordId: CKRecord.ID, reason: CKQueryNotification.Reason) {
fetchAndSaveRemoteDataFromCloudKit(recordId: recordId, reason: reason, userData: self)
}
}
in AppDelegate:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
let notification: CKNotification = CKNotification(fromRemoteNotificationDictionary: userInfo)!
if notification.notificationType == .query {
let queryNotification = notification as! CKQueryNotification
let recordId = queryNotification.recordID
let reason: CKQueryNotification.Reason = queryNotification.queryNotificationReason
/// reasons:
/// .recordCreated, .recordUpdated, .recordDeleted
UserData().saveFetchedItem(recordId: recordId!, reason: reason)
}
completionHandler(.newData)
}
In fetchAndSaveRemoteDataFromCloudKit, I'm passing the UserData in order to save the item received and it works. The problem is, I show the items on a List and the list doesn't refresh, even when I print the userData.items and the new item is there.
Is there a connection between AppDelegate and SceneDelegate in order to refresh the scene/window?

Related

Firebase Phone Auth not receiving silent notification on SwiftUI

I am trying to implement phone auth in SwiftUI using Firebase. I keep getting the following error in the console:
If app delegate swizzling is disabled, remote notifications received by UIApplicationDelegate need to be forwarded to FIRAuth's canHandleNotificaton: method.
I have not disabled swizzling from what I know and I have tried different things.
I set-up my firebase project correctly, anyone else facing the same problem?
I looked up in the documentation and I found a part about this:
func application(_ application: UIApplication,
didReceiveRemoteNotification notification: [AnyHashable : Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
if Auth.auth().canHandleNotification(notification) {
completionHandler(.noData)
return
}
// This notification is not auth related, developer should handle it.
}
But I don't know where to put it or how to declare it.
Tried doing the following but nothing changes:
import SwiftUI
import Firebase
import GoogleMaps
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication,
didReceiveRemoteNotification notification: [AnyHashable : Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
if Auth.auth().canHandleNotification(notification) {
completionHandler(.noData)
return
}
// This notification is not auth related, developer should handle it.
}
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
for urlContext in URLContexts {
let url = urlContext.url
Auth.auth().canHandle(url)
}
// URL not auth related, developer should handle it.
}
}
#main
struct partidulverdeApp: App {
#UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
init() {
FirebaseApp.configure()
GMSServices.provideAPIKey("AIzaSyAaze5cpEcJUgw2WFgLhlTWYr9ZP4fyDNk")
}
var body: some Scene {
WindowGroup {
MainView()
.onOpenURL(perform: { url in
Auth.auth().canHandle(url)
})
}
}
}

iOS 12 not received FCM notifications

Hi I'm using XCode version: 10.1 (10B61) and iPhone SE with iOS version: 12.0.1 (16A404), I installed properly all configuration as documentation explained, I uploaded the Auth .p8 certificate and the p.12 certificates of development and production, but when I try to send a push notification from Firebase console I don't receive any, am I missing something? or I did some wrong? any help, please?
//
// AppDelegate.swift
// SpriteKit Game Demo
//
// Created by Dennis Mostajo on 9/2/18.
// Copyright © 2018 Mostys Studios.. All rights reserved.
//
import UIKit
import Fabric
import Crashlytics
import Firebase
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
var window: UIWindow?
var navigationVC: UINavigationController?
let gcmMessageIDKey = "gcm.message_id"
override init() {
// set Firebase configuration
FirebaseApp.configure()
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
debugPrint("didFinishLaunchingWithOptions")
Fabric.with([Crashlytics.self])
DataBaseHelper.DBUpdate() // Run migrations
// Enable Push Notifications
Messaging.messaging().delegate = self
Messaging.messaging().shouldEstablishDirectChannel = 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()
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.
debugPrint("applicationWillResignActive")
}
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.
debugPrint("applicationDidEnterBackground")
}
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.
debugPrint("applicationWillEnterForeground")
}
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.
debugPrint("applicationDidBecomeActive")
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
debugPrint("applicationWillTerminate")
}
// MARK: - FIREBASE
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any])
{
Messaging.messaging().appDidReceiveMessage(userInfo)
if let messageID = userInfo[gcmMessageIDKey]
{
debugPrint("Message ID: \(messageID)")
}
// Print full message.
debugPrint(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void)
{
Messaging.messaging().appDidReceiveMessage(userInfo)
if let messageID = userInfo[gcmMessageIDKey]
{
debugPrint("Message ID: \(messageID)")
}
// Print full message.
debugPrint(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error)
{
debugPrint("Unable to register for remote notifications: \(error.localizedDescription)")
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
debugPrint("didRegisterForRemoteNotificationsWithDeviceToken: DATA")
let token = String(format: "%#", deviceToken as CVarArg)
debugPrint("*** deviceToken: \(token)")
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
debugPrint("deviceTokenString: \(deviceTokenString)")
Messaging.messaging().apnsToken = deviceToken
// debugPrint("Firebase Token:",InstanceID.instanceID().token() as Any)
}
}
// [START ios_10_message_handling]
#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) {
//Handle the notification ON APP
Messaging.messaging().appDidReceiveMessage(notification.request.content.userInfo)
completionHandler([.sound,.alert,.badge])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
//Handle the notification ON BACKGROUND
Messaging.messaging().appDidReceiveMessage(response.notification.request.content.userInfo)
completionHandler()
}
}
// [END ios_10_message_handling]
extension AppDelegate : MessagingDelegate {
// [START refresh_token]
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
InstanceID.instanceID().instanceID
{
(result, error) in
if let error = error
{
debugPrint("Error fetching remote instange ID: \(error)")
}
else if let result = result
{
debugPrint("Remote instance ID token: \(result.token)")
}
}
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.
}
// [END refresh_token]
// [START ios_10_data_message]
// Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground.
// To enable direct data messages, you can set Messaging.messaging().shouldEstablishDirectChannel to true.
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
debugPrint("Received data message: \(remoteMessage.appData)")
}
// [END ios_10_data_message]
}
Podfile:
# Uncomment the next line to define a global platform for your project
platform :ios, '10.0'
def shared_pods
pod 'Fabric'
pod 'Crashlytics'
pod 'Alamofire', '~> 4.7'
pod 'RealmSwift'
pod 'SwiftyJSON'
pod 'PKHUD', '~> 5.0'
pod 'Siren'
pod 'Firebase/Core'
pod 'Firebase/Messaging'
pod 'Firebase/DynamicLinks'
pod 'Firebase/Crash'
end
target 'Sprite Kit Game' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
# Pods for Sprite Kit Game
shared_pods
end
target 'Sprite Kit GameTests' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
# Pods for testing
shared_pods
end
target 'Sprite Kit GameUITests' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
# Pods for testing
shared_pods
end
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
# This works around a unit test issue introduced in Xcode 10.
# We only apply it to the Debug configuration to avoid bloating the app size
if config.name == "Debug" && defined?(target.product_type) && target.product_type == "com.apple.product-type.framework"
config.build_settings['ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES'] = "YES"
end
end
end
end
no notifications are received neither by foreground nor background, any help, please?
The issue was resolved to update this part of the code handling the message/push notification from Firebase console
// [START ios_10_message_handling]
#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
if let messageID = userInfo[gcmMessageIDKey] {
debugPrint("Message ID: \(messageID)")
}
debugPrint(userInfo)
//Handle the notification ON APP
Messaging.messaging().appDidReceiveMessage(userInfo)
completionHandler([.sound,.alert,.badge])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
if let messageID = userInfo[gcmMessageIDKey] {
debugPrint("Message ID: \(messageID)")
}
//Handle the notification ON BACKGROUND
Messaging.messaging().appDidReceiveMessage(userInfo)
completionHandler()
}
}
// [END ios_10_message_handling]
the issue was tracked on GitHub
Make sure you updated iOS Deployment Target in the NotificationService settings

Push notification is not working when app is in background (minimized) - iOS

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.
If it works with non-Silent notification then all it means is:
Then payload is not correctly setup. Based on the answers provided to this question I'd just alter the placement of the 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.
I'd also make sure all the correct capabilities in Xcode are set (Enabled Remote notification, Background Fetches in Xcode setup, Enabled Push Notification). As mentioned previously uncheck and recheck all of them again.
And make sure Background App refresh is enabled for your app. This is NOT the same with your notifications. Obviously make sure your notifications are also enabled.:
But if you tried everything and it just doesn't work for 11.3 then it might be a bug. There is this other open question mentioned the same issue of yours. Run the app directly from tapping the app, ie not launching from Xcode and then use the console to see what it's logging related to the silent notification. If you're getting something like this:
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!

How to implement Push notification in xcode 7.3

I want to implement older Firebase notification any link for older SDKs and old Pod version
I am using Xcode 7.3 and I want to implement firebase push notification but
due to latest pod I can't run project and comes error in FIRMessagingDelegate and FIRInstanceID I install both pod but method is not working.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
let notificationTypes: UIUserNotificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]
let pushNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)
application.registerUserNotificationSettings(pushNotificationSettings)
application.registerForRemoteNotifications()
return true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
print("DEVICE TOKEN = \(deviceToken)")
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print(error)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
print(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 throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(_application: UIApplication, didReceiveRemoteNotification userInfo: [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)
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler()
}
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
}
Finding pod Version in change log and install pod
pod 'Firebase', '~> 3.10'
pod 'FirebaseMessaging', '~> 1.0’
and after install pod
letest pod dose't suppot userNotifications Framwork

Firebase Notification with Xcode 8 iOS 10 Swift 3

I try to follow the tutorial to configure my iOS app to receive notifications from Firebase. I'm able to receive the message when the app in foreground, but NOT in background.
Here is the data format I received when the app in foreground mode:
[AnyHashable("notification"): {
body = 80;
e = 1;
}, AnyHashable("from"): 7151xxxxxx8, AnyHashable("collapse_key"): me.caoyang.iOSPushNotification]
I have:
Enabled the Push Notifications, Background Modes (Remote notifications) and Keychain Sharing under Capabilities.
Toggled FirebaseAutomaticScreenReportingEnabled and FirebaseAppDelegateProxyEnabled under Info.plist with YES or NO option many times.
Includes GoogleService-Info.plist into project
and yes, I uploaded the .p12 file.
My questions:
What should be the value of variable gcmMessageIDKey?
What can I do or debug or try to make it work?
ViewController.swift file
override func viewDidLoad() {
super.viewDidLoad()
//_ = FIRInstanceID.instanceID().token()
//FIRMessaging.messaging().subscribe(toTopic: "/topics/news")
}
#IBAction func btnPressed(_ sender: Any) {
let token = FIRInstanceID.instanceID().token()
print("token: \(token)")
}
AppDelegate.swift file
//
// Copyright (c) 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import UserNotifications
import Firebase
import FirebaseInstanceID
import FirebaseMessaging
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Register for remote notifications. This shows a permission dialog on first run, to
// show the dialog at a more appropriate time move this registration accordingly.
// [START register_for_notifications]
if #available(iOS 10.0, *) {
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()
// [END register_for_notifications]
FIRApp.configure()
// [START add_token_refresh_observer]
// Add observer for InstanceID token refresh callback.
NotificationCenter.default.addObserver(self,
selector: #selector(self.tokenRefreshNotification),
name: .firInstanceIDTokenRefresh,
object: nil)
// [END add_token_refresh_observer]
return true
}
// [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
// 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
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
// [END receive_message]
// [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]
// [START connect_to_fcm]
func connectToFcm() {
// Won't connect since there is no token
guard FIRInstanceID.instanceID().token() != nil else {
return;
}
// Disconnect previous FCM connection if it exists.
FIRMessaging.messaging().disconnect()
FIRMessaging.messaging().connect { (error) in
if error != nil {
print("Unable to connect with FCM. \(error)")
} else {
print("Connected to FCM.")
}
}
}
// [END connect_to_fcm]
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Unable to register for remote notifications: \(error.localizedDescription)")
}
// 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 token can be paired to
// the InstanceID token.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("APNs token retrieved: \(deviceToken)")
// With swizzling disabled you must set the APNs token here.
// FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)
}
// [START connect_on_active]
func applicationDidBecomeActive(_ application: UIApplication) {
connectToFcm()
}
// [END connect_on_active]
// [START disconnect_from_fcm]
func applicationDidEnterBackground(_ application: UIApplication) {
FIRMessaging.messaging().disconnect()
print("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,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
// Change this to your preferred presentation option
completionHandler([.alert, .badge, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler()
}
}
// [END ios_10_message_handling]
// [START ios_10_data_message_handling]
extension AppDelegate : FIRMessagingDelegate {
// Receive data message on iOS 10 devices while app is in the foreground.
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
print(remoteMessage.appData)
}
}
// [END ios_10_data_message_handling]

Resources