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

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

Related

Getting FCM key nil from Firebase cloud messaging

Am trying to fetch FCM key for push notification from Firebase cloud messaging but am getting nil & error which i mention below
**
Error :- APNS device token not set before retrieving FCM Token for Sender ID '836092823410'. Notifications to this FCM Token will not be delivered over APNS.Be sure to re-retrieve the FCM token once the APNS device token is set.
**
Google Plist File
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CLIENT_ID</key>
<string>836092823410-d76r5bkjrusfmgo6rskqo81l4mk7vmp4.apps.googleusercontent.com</string>
<key>REVERSED_CLIENT_ID</key>
<string>com.googleusercontent.apps.836092823410-d76r5bkjrusfmgo6rskqo81l4mk7vmp4</string>
<key>API_KEY</key>
<string>AIzaSyDpP1n_NRqj9c_Mq-pA2PlRez7AnVM5buw</string>
<key>GCM_SENDER_ID</key>
<string>836092823410</string>
<key>PLIST_VERSION</key>
<string>1</string>
<key>BUNDLE_ID</key>
<string>com.iai.tracker</string>
<key>PROJECT_ID</key>
<string>crucial-audio-334611</string>
<key>STORAGE_BUCKET</key>
<string>crucial-audio-334611.appspot.com</string>
<key>IS_ADS_ENABLED</key>
<false/>
<key>IS_ANALYTICS_ENABLED</key>
<false/>
<key>IS_APPINVITE_ENABLED</key>
<true/>
<key>IS_GCM_ENABLED</key>
<true/>
<key>IS_SIGNIN_ENABLED</key>
<true/>
<key>GOOGLE_APP_ID</key>
<string>1:836092823410:ios:0312dc35c45b23b9e37feb</string>
</dict>
</plist>
Delegate File
import UIKit
import GoogleMaps
import Firebase
import GooglePlaces
import Highcharts
enum BuildTypes: String {
case jsd = "JSD"
case fleetPolice = "FleetPolice"
case veyron = "Veyron"
case jbd = "JBD"
case gpsTracker = "GPSTracker"
case roadLookUp = "RoadLookUp"
case iaitrack = "IAITrack"
}
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate {
var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id";
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//Going through different build type
let buildType: String = Bundle.main.infoDictionary?["BUILD_TYPE"] as? String ?? "Debug"
print("Build type: - ",buildType)
NotificationCenter.default.addObserver(self, selector: #selector(self.notAuthorized), name: HTTPUtil.NotAuthorizedNotification, object: nil);
switch buildType {
case BuildTypes.jsd.rawValue, BuildTypes.fleetPolice.rawValue:
print("JSD")
GMSServices.provideAPIKey("AIzaSyBKsjff4VNWTyu8X3UTYXOBazO0jt_Cnpw");
GMSPlacesClient.provideAPIKey("AIzaSyBKsjff4VNWTyu8X3UTYXOBazO0jt_Cnpw");
case BuildTypes.veyron.rawValue, BuildTypes.jbd.rawValue, BuildTypes.gpsTracker.rawValue:
GMSServices.provideAPIKey("AIzaSyCRWtSQIUsoNhFwMMdeFRX0A74rooHskBg");
GMSPlacesClient.provideAPIKey("AIzaSyCRWtSQIUsoNhFwMMdeFRX0A74rooHskBg");
case BuildTypes.iaitrack.rawValue:
GMSServices.provideAPIKey("AIzaSyC2qDNCajLm1Kq_AuZTS5tE0xJ73R1RTkA");
GMSPlacesClient.provideAPIKey("AIzaSyC2qDNCajLm1Kq_AuZTS5tE0xJ73R1RTkA");
default:
print("REst")
GMSServices.provideAPIKey("AIzaSyAgaZm9nk4RcfgZ0O0R9UgxJ7PRLZt0RB4");
GMSPlacesClient.provideAPIKey("AIzaSyAgaZm9nk4RcfgZ0O0R9UgxJ7PRLZt0RB4");
}
FirebaseApp.configure()
Messaging.messaging().delegate = self
let t = Messaging.messaging().token { token, error in
if (token != nil) {
print(token)
} else {
print(error)
}
}
let token = Messaging.messaging().fcmToken
print("FCM token: \(token ?? "")")
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()
HIChartView.preload()
let u = UserService.getActiveUserLocalCache();
Configuration.setBaseUrl(baseUrl: u?.baseUrl ?? "https://api.fleethunt.in/");
return true
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
debugPrint(fcmToken);
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
#objc func notAuthorized(){
if let window = self.window{
let mainTabController = window.rootViewController as! MainTabBarController;
mainTabController.selectedIndex = 0;
let home = (mainTabController.viewControllers?[0] as! UINavigationController).viewControllers[0] as! HomeViewController;
home.showLoginVC();
window.makeToast("Not Authorized. You have been logged out");
}
}
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.
self.updateFcmToken();
let u = UserService.getActiveUserLocalCache();
Configuration.setBaseUrl(baseUrl: u?.baseUrl ?? "https://api.fleethunt.in/");
}
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:.
}
// 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 FCM registration token.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
self.updateFcmToken();
// With swizzling disabled you must set the APNs token here.
// Messaging.messaging().apnsToken = deviceToken
}
func updateFcmToken() -> Void{
let mute = UserDefaults.standard.bool(forKey: "mute") ?? false
print(mute);
FCMService.updateFCM(mute: mute) { (resp) in
}
}
var orientationLock = UIInterfaceOrientationMask.portrait
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return self.orientationLock
}
struct AppUtility {
static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
if let delegate = UIApplication.shared.delegate as? AppDelegate {
delegate.orientationLock = orientation
}
}
static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {
self.lockOrientation(orientation)
UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
}
}
}
#available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// [START refresh_token]
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
self.updateFcmToken();
}
// [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: MessagingDelegate) {
print("Received data message: \(remoteMessage.description)")
}
// [END ios_10_data_message]
// 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 message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
// Change this to your preferred presentation option
completionHandler([])
}
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()
}
}

Why the push notification don‘t work in iOS with Firebase from device to device?

I have created the Production Identifier and all this stuff and it has worked but sometime later suddenly it doesn't work anymore. And I have nothing changed in the Notification Area in my code.
From Firebase Cloud Messaging - Test Sending works fine. But from Device to Device not.
import UIKit
import Firebase
import FirebaseMessaging
import FirebaseInstanceID
import UserNotifications
import AVFoundation
import GoogleMobileAds
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
static let NOTIFICATION_KEY = "https://gcm-http.googleapis.com/gcm/send"
static var DEVICE_ID = String()
static let SERVER_KEY = "AAAACucgXz8:APA91bE_vEyKiqR34sruY2f5tetjj_DrwVi42v9tL015tLEOZmwBh-q7oWsNXUrpR0S9XBCrbxMJtgUu70xNAyDeouNvxn1kHKll2Dcwzxbf40lbappxs-o6IDvHVvEajzX5Dzsq8MW8"
static var EXITAPP = Bool()
static var LIKESCOUNTER = Int()
var dateForm = DateFormatter()
var timeFormatter = DateFormatter()
static var INSERTTIME = false
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible() //Damit wir die ganzen Views selber bearbeiten können.
window?.rootViewController = UINavigationController(rootViewController: ViewController())
if #available(iOS 10.0, *){
UNUserNotificationCenter.current().delegate = self
let option: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: option) { (bool, err) in
}
}
application.registerForRemoteNotifications()
UIApplication.shared.applicationIconBadgeNumber = 0
GADRewardBasedVideoAd.sharedInstance().load(GADRequest(), withAdUnitID: "ca-app-pub-3940256099942544/1712485313")
if #available(iOS 9.0, *){
application.isStatusBarHidden = true //HIDE STATUS BAR
}
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.
insertOnlineActivity(online: false)
connectToFCM()
}
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.
AppDelegate.EXITAPP = true
// if AppDelegate.INSERTTIME{
// insertLastLikedTime()
// }
insertOnlineActivity(online: false)
connectToFCM()
}
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.
insertOnlineActivity(online: true)
connectToFCM()
}
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.
insertOnlineActivity(online: true)
connectToFCM()
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String){
guard let newToken = InstanceID.instanceID().token() else {return}
AppDelegate.DEVICE_ID = newToken
connectToFCM()
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
let notification = response.notification.request.content.body
print(notification)
completionHandler()
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
guard let newToken = InstanceID.instanceID().token() else {return}
//let newToken = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
AppDelegate.DEVICE_ID = newToken
connectToFCM()
Messaging.messaging().setAPNSToken(deviceToken, type: .unknown)
}
func connectToFCM(){
Messaging.messaging().shouldEstablishDirectChannel = true
}
This is how I call the Notification
fileprivate func setUpPushNotifications(fromDeviceID: String){
let message = self.userName + " has sent you a voice message."
let title = "New Message"
let toDeviceID = fromDeviceID
var headers:HTTPHeaders = HTTPHeaders()
headers = ["Content-Type":"application/json","Authorization":"key=\(AppDelegate.SERVER_KEY)"]
let notifications = ["to" : "\(toDeviceID)" , "notification":["body":message,"title":title,"badge":1,"sound":"default"]] as [String : Any]
request(AppDelegate.NOTIFICATION_KEY as URLConvertible, method: .post as HTTPMethod, parameters: notifications, encoding: JSONEncoding.default, headers: headers).response { (response) in
print(response)
}
}

Firebase - Swift 4: Message sent but not received

Ran pod update on the terminal to update my firebase. However i don't receive FCM's
This is my app delegate code:
import UIKit
import Firebase
import FirebaseFirestore
import StoreKit
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
var window: UIWindow?
override init() {
super.init()
FirebaseApp.configure()
// not really needed unless you really need it FIRDatabase.database().persistenceEnabled = true
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
Auth.auth().signInAnonymously() { (authResult, error) in
// ...
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
UIApplication.shared.statusBarStyle = .default
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = mainStoryboard.instantiateViewController(withIdentifier: "gateway") as! gatewayViewController
window!.rootViewController = viewController
return true
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(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.
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
// if let messageID = userInfo[gcmMessageIDKey] {
// print("Message ID: \(messageID)")
// }
// Print full message.
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
//if let messageID = userInfo[gcmMessageIDKey] {
// print("Message ID: \(messageID)")
//}//
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
But when trying to send a message on my console.firebase.com it gets labeled as "Completed" but my iPhone 6S don't shows the notification.
Notifications are also enabled in app capabilities
I need your help
I think you're not setting your APN token. Push your APNs token.
func application(_ application: UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenParts = deviceToken.map { //data -> String in
return String(format: "%02.2hhx", $0)
}
Messaging.messaging().apnsToken = deviceToken
Messaging.messaging().setAPNSToken(deviceToken, type: .unknown)
UserDefaults.standard.synchronize()
}

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 firebase remote notifications Not Receiving, xCode 9.0

Good day everyone. First post, so I'll do my best:
I have been using stackoverflow for a while now trying to figure this out with the existing questions, with no success.
I am trying to do a simple Firebase remote push notification using xCode 9.0 beta 5. From the consol, it shows completed, but I'm not seeing any of the notifications make it to my app. I have checked the certificates, the swift capabilities, etc, and everything seems fine. Still no success. Here is may AppDelegate code. I really don't know where to go from here so any help would be appreciated.. I actually had a very simplistic version working on a released version of swift, and it doesn't work anymore either, so I believe it has something to do with the code:
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate, MessagingDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
var manager = CLLocationManager()
let gcmMessageIDKey = "gcm.message_id"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// Added by Ryan to support FB login:
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
// Added by Ryan to support Twitter login:
Twitter.sharedInstance().start(withConsumerKey:"ecd84HTwPAdHMhCENbM1o2IfQ", consumerSecret:"W3HmRzYpBOMmtDpHn6J3LCdV67VVeqkz87FvqOzSSRLrvZI6Ju")
// Set the CLLocationManager accuracy:
manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
manager.delegate = self
manager.requestAlwaysAuthorization()
manager.allowsBackgroundLocationUpdates = true
manager.pausesLocationUpdatesAutomatically = false
manager.distanceFilter = USER_DISTANCE_FILTER // meters until postion updated
// Initialize Firebase Remote Notifications:
// Request Authorizations:
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (isGranted, err) in
if err != nil {
print(err!)
return
} else {
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
// Configure Firebase:
FirebaseApp.configure()
UNUserNotificationCenter.current().delegate = self
Messaging.messaging().delegate = self
connectToFMC()
return true
}
func connectToFMC() {
// Establish a direct connection the the FMC (Firebase Messaging Controller):
Messaging.messaging().shouldEstablishDirectChannel = true
}
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.
print("Entering Background")
self.manager.startUpdatingLocation()
}
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.
var geoFireActiveAgents: GeoFire!
var geoFireActiveAgentsRef: DatabaseReference!
geoFireActiveAgentsRef = DataService.ds.REF_ACTIVEAGENTS
geoFireActiveAgents = GeoFire(firebaseRef: geoFireActiveAgentsRef)
// Make a direct connection to Firebase Messaging Controller for Remote messaging:
connectToFMC()
// When the app comes out of sleep, we need to update the location data to the global variable and the database in case the user moved while asleep:
if CLLocationManager.locationServicesEnabled() {
// log the active position to the Primary User Info:
if let activeLocation = manager.location {
PrimaryUserInfo.primUser.activeLocation = activeLocation
if let userID = Auth.auth().currentUser?.uid {
if let userLatitude = PrimaryUserInfo.primUser.activeLocation.coordinate.latitude as Optional {
if let userLongitude = PrimaryUserInfo.primUser.activeLocation.coordinate.longitude as Optional {
// If the user is an active Agent, log his/her location in GeoFire:
if PrimaryUserInfo.primUser.activeAgent {
geoFireActiveAgents.setLocation(CLLocation(latitude: userLatitude, longitude: userLongitude), forKey: userID)
// Add a timestamp to see when the Agent was last active:
let timeStamp = Date().timeIntervalSince1970
let values = ["timestamp": timeStamp] as [String : Any]
DataService.ds.REF_ACTIVEAGENTS.child(userID).updateChildValues(values, withCompletionBlock: { (err, ref) in
if err != nil {
print(err!)
}
})
}
}
}
}
}
}
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
print("Application Terminating")
// Remove the active agent from the Firebase Database:
DataService.ds.REF_ACTIVEAGENTS.child(PrimaryUserInfo.primUser.userID).removeValue()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations location: CLLocation){
// Send background location to Firebase Database when there is a significant location change:
self.sendBackgroundLocationToServer(location: location)
}
func sendBackgroundLocationToServer(location: CLLocation) {
// This section updates the Firebase Database location while app is in the background.
// It purposefuly uses a background task to 'wake up' and spit out the data.
var bgTask = UIBackgroundTaskIdentifier()
bgTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
UIApplication.shared.endBackgroundTask(bgTask)
})
var userLatitude = CLLocationDegrees()
var userLongitude = CLLocationDegrees()
if CLLocationManager.authorizationStatus() == .authorizedAlways {
userLatitude = (manager.location?.coordinate.latitude)!
userLongitude = (manager.location?.coordinate.longitude)!
let geoFireActiveAgents: GeoFire!
let geoFireActiveAgentsRef: DatabaseReference!
geoFireActiveAgentsRef = DataService.ds.REF_ACTIVEAGENTS
geoFireActiveAgents = GeoFire(firebaseRef: geoFireActiveAgentsRef)
let userID = PrimaryUserInfo.primUser.userID
geoFireActiveAgents.setLocation(CLLocation(latitude: userLatitude, longitude: userLongitude), forKey: userID)
}
if (bgTask != UIBackgroundTaskInvalid)
{
UIApplication.shared.endBackgroundTask(bgTask)
bgTask = UIBackgroundTaskInvalid
}
}
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
// New Token automatically established:
let newToken = InstanceID.instanceID().token()
print("newToken = \(newToken!)")
connectToFMC()
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (_ options: UNNotificationPresentationOptions) -> Void) {
// custom code to handle push while app is in the foreground
print("Handle push from foreground\(notification.request.content.userInfo)")
let dict = notification.request.content.userInfo["aps"] as! NSDictionary
let d : [String : Any] = dict["alert"] as! [String : Any]
let body : String = d["body"] as! String
let title : String = d["title"] as! String
print("Title:\(title) + body:\(body)")
self.showAlertAppDelegate(title: title,message:body,buttonTitle:"ok",window:self.window!)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
// if you set a member variable in didReceiveRemoteNotification, you will know if this is from closed or background
print("Handle push from background or closed\(response.notification.request.content.userInfo)")
}
func showAlertAppDelegate(title: String,message : String,buttonTitle: String,window: UIWindow){
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: buttonTitle, style: UIAlertActionStyle.default, handler: nil))
window.rootViewController?.present(alert, animated: false, completion: nil)
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
if let token = InstanceID.instanceID().token() {
print("Token: \(token)")
}
}
}