I have done push notification using FCM on the app side. When the user taps on the notification it navigates to specific viewController from the app side to custom SDK. I have tried many ways but viewController is not showing but all functionalities are loaded successfully.
1. First attempt: [Notification tap is detected and passed data from the app side to framework. Loaded particular viewController functionalities but viewController are not showing.]
When user tap notification from the app side, it will send data to the framework to show a particular viewController.
here is the code for the app side:
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
if(application.applicationState == .active){
print("user tapped the notification bar when the app is in foreground")
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print("didReceive notification tapped",userInfo)
TaskName = userInfo[taskName] as? String ?? ""
print("TaskName::::", TaskName ?? "")
ProcessInstanceId = userInfo[processInstanceId] as? String ?? ""
print("ProcessInstanceId::::", ProcessInstanceId ?? "")
processDefinitionName = userInfo[ProcessDefinitionId] as? String ?? ""
print("processDefinitionName::::", processDefinitionName ?? "")
TaskID = userInfo[taskId] as? String ?? ""
print("taskID::::", TaskID ?? "")
FormKey = userInfo[formKey] as? String ?? ""
print("FormKey::::", FormKey ?? "")
Types = userInfo[type] as? String ?? ""
print("Type::::", Types ?? "")
Title = userInfo[title] as? String ?? ""
print("Title::::", Title ?? "")
Body = userInfo[body] as? String ?? ""
print("Body::::", Body ?? "")
CreatedDate = userInfo[created] as? String ?? ""
print("created:::", CreatedDate ?? "")
AFlowBuilder(self).callFormView(taskName: TaskName ?? "", processInstanceID: ProcessInstanceId ?? "", ProcessDefinitionName: processDefinitionName ?? "", taskId: TaskID ?? "", formKey: FormKey ?? "", title: Title ?? "", type: Types ?? "", body: Body ?? "", created: CreatedDate ?? "", formStatus: false)
}
completionHandler()
}
Here is the code from the framework side:
private var taskViewNew: UIViewController?
public func callFormView(taskName: String, processInstanceID: String, ProcessDefinitionName: String, taskId: String, formKey: String, title: String, type: String, body: String, created: String, formStatus: Bool){
let newNotification = makeSaveNotification(taskName: taskName, processInstanceID: processInstanceID, ProcessDefinitionName: ProcessDefinitionName, taskId: taskId, formKey: formKey, title: title, type: type, body: body, created: created, formStatus: formStatus)
let realm = try! Realm()
// let realmData = realm.objects(NotificationRealmModel.self).filter("name = \(userNameRealm ?? "")").first!
try! realm.write {
realm.add(newNotification)
print("ream notification saved path url:: call form view", realm.configuration.fileURL ?? "")
}
let controller = CreateCardViewController()
let str = formKey
let result = String(str.dropFirst(7))
print(result)
let s = String(result.dropLast(10))
print("newFormKey call form view", s )
let v = convap(text: s)
controller.processInstanceId = processInstanceID
controller.cardName = ""
controller.TaskIdValue = taskId
controller.formKey = v
controller.tabName = "NotificationTapped"
controller.fullFormKey = formKey
self.taskViewNew?.addChild(controller)
self.taskViewNew?.view.addSubview(controller.view)
controller.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
// controller.didMove(toParent: taskViewNew)
taskViewNew?.present(controller, animated: true, completion: nil)
}
Second attempt: [Notification detected in the app side and passed value to viewController. And, Inside viewController framework method is called to load framework viewController but all functionality is loaded successfully but the view is not loaded]
Here is the code from the app side:
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
if(application.applicationState == .active){
print("user tapped the notification bar when the app is in foreground")
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print("didReceive notification tapped",userInfo)
TaskName = userInfo[taskName] as? String ?? ""
print("TaskName::::", TaskName ?? "")
ProcessInstanceId = userInfo[processInstanceId] as? String ?? ""
print("ProcessInstanceId::::", ProcessInstanceId ?? "")
processDefinitionName = userInfo[ProcessDefinitionId] as? String ?? ""
print("processDefinitionName::::", processDefinitionName ?? "")
TaskID = userInfo[taskId] as? String ?? ""
print("taskID::::", TaskID ?? "")
FormKey = userInfo[formKey] as? String ?? ""
print("FormKey::::", FormKey ?? "")
Types = userInfo[type] as? String ?? ""
print("Type::::", Types ?? "")
Title = userInfo[title] as? String ?? ""
print("Title::::", Title ?? "")
Body = userInfo[body] as? String ?? ""
print("Body::::", Body ?? "")
CreatedDate = userInfo[created] as? String ?? ""
print("created:::", CreatedDate ?? "")
}
window = UIWindow(frame: UIScreen.main.bounds)
let homeViewController = ViewController()
homeViewController.Body = Body
homeViewController.CreatedDate = CreatedDate
homeViewController.FormKey = FormKey
homeViewController.processDefinitionName = processDefinitionName
homeViewController.ProcessInstanceId = ProcessInstanceId
homeViewController.TaskID = TaskID
homeViewController.Title = Title
homeViewController.Types = Types
homeViewController.view.backgroundColor = UIColor.red
window!.rootViewController = homeViewController
window!.makeKeyAndVisible()
completionHandler()
}
Here is the code viewController from the app side, it will load the framework viewController method.
Attempt 1:
override func viewDidAppear(_ animated: Bool) {
let controller = CreateCardViewController()
let str = FormKey
let result = String(str?.dropFirst(7) ?? "")
print(result)
let s = String(result.dropLast(10))
print("newFormKey call form view", s )
let v = convap(text: s)
controller.processInstanceId = ProcessInstanceId
controller.cardName = ""
controller.TaskIdValue = TaskID
controller.formKey = v
controller.tabName = "NotificationTapped"
print(controller.tabName)
controller.fullFormKey = FormKey
add(asChildViewController: controller)
}
private func add(asChildViewController viewController: UIViewController) {
// Add Child View Controller
addChild(viewController)
// Add Child View as Subview
view.addSubview(viewController.view)
// Configure Child View
viewController.view.frame = view.bounds
viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
// Notify Child View Controller
viewController.didMove(toParent: self)
}
Attempt: 2
override func viewDidAppear(_ animated: Bool) {
print("Presenting next...")
let controller = CreateCardViewController()
let str = FormKey
let result = String(str?.dropFirst(7) ?? "")
print(result)
let s = String(result.dropLast(10))
print("newFormKey call form view", s )
let v = convap(text: s)
controller.processInstanceId = ProcessInstanceId
controller.cardName = ""
controller.TaskIdValue = TaskID
controller.formKey = v
controller.tabName = "NotificationTapped"
print(controller.tabName)
controller.fullFormKey = FormKey
present(controller, animated: true, completion: nil)
}
Any help much appreciated pls...
I have such task currently maybe it is a little bit simpler but this is my code:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
if let navigationController = window?.rootViewController as? UINavigationController {
navigationController.popToRootViewController(animated: false)
if let someViewController = navigationController.storyboard?.instantiateViewController(withIdentifier: "SomeViewController") as? SomeViewController {
navigationController.pushViewController(someViewController, animated: true)
}
}
}
In my case, it works fine because I have UINavigationController as a root of my app, and I manage my navigation through it. This is important to be sure what you have on your stack of views right now and how to clear it.
Also, you can see that I use this line for instantiating my new ViewController
if let someViewController = navigationController.storyboard?.instantiateViewController(withIdentifier: "SomeViewController") as? SomeViewController
But this is not important, just be sure that your ViewController is correctly initiated.
Good luck.
I used the top view controller to present the desired view.
To fetch top view controller:
func topController() -> UIViewController {
if var topController = UIApplication.shared.keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
return topController
}
return (UIApplication.shared.keyWindow?.rootViewController)!
}
Then on receiving notification:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print(userInfo)
guard Utility.shared.userInfo != nil else { return }
let vc : EventDetailVC = EVENTSSTORYBOARD.viewController(id: "EventDetailVC") as! EventDetailVC
vc.eventID = event_id
vc.eventType = EventType.Invite
let nav = UINavigationController(rootViewController: vc)
nav.modalPresentationStyle = .fullScreen
self.topController().present(nav, animated: true, completion: nil)
}
Let me know if it works for you.
Use NotificationCenter create a custom NSNotification.Name and subscribe your viewcontroller to the created notification name using
NotificationCenter.default.addObserver(self, selector: #selector(openView), name: <<custom notification name>>, object: nil)
after that using the selector function you can pass all the parameters to the view controller
#objc func openView(notification: Notification){}
and in didFinishLaunchingWithOptions post to the above custom notification using this
let userInfo = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification]
if (userInfo != nil){
DispatchQueue.main.asyncAfter(deadline: .now() + 0.9) {
NotificationCenter.default.post(name: <<custom notification name>>, object: nil, userInfo: userInfo as! [AnyHashable : Any]?)
}
}
if you have multiple viewcontrollers that needs to be open you can create a base view controller class and put above code in the base class and extend the viewcontrollers by the base class
Related
I am trying to use data from firebase to populate buttons on the UI. Everything works as expected except the button title is not updating. Any ideas on how to fix this?
#IBAction func addNewTapped(_ sender: Any) {
readOneDay2(lastMonday(trackerDate), completion: { message in
let lastHourRead = message
print(message)
self.lastHour1.setTitle(lastHourRead, for: UIControl.State.application)
})
}
func readOneDay2 (_ mydate: Date, completion: #escaping (_ message: String) -> Void){
var db: DatabaseReference!
db = Database.database().reference()
var totalComb: Double = 0.0
let userID = Auth.auth().currentUser?.uid
db.child("TimesheetData").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let dict = snapshot.value as? NSDictionary
for (key, value) in dict! {
let myvalue = value as? [String: Any]
let compDate: String = myvalue!["timeSheetDate"]! as! String
if compDate == dateStringer(mydate) {
let sHours: String = myvalue!["hours"]! as! String
let sOverTime: String = myvalue!["overTime"]! as! String
let sDoubleTime: String = myvalue!["doubleTime"]! as! String
let dHours: Double = Double(sHours)!
let dOverTime: Double = Double(sOverTime)!
let dDoubleTime: Double = Double(sDoubleTime)!
totalComb = totalComb + dHours + dOverTime + dDoubleTime
print(key)
}
}
print("First Sum " + String(totalComb))
DispatchQueue.main.async {
completion(String(totalComb))
}
}) { (error) in
print(error.localizedDescription)
}
}
As per #Virender said,
Change UIControl.State.application to UIControl.State.normal
DispatchQueue.main.async {
self.lastHour1.setTitle(lastHourRead, for:.normal)
}
I'm working on app that includes a messenger feature ,the problem is every time i tap on the push notification im directed to the app itself rather than the message itself, i believe the code is correct, might it be a matter of swift version ....?
// AppDelegate
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
let gcmMessageIDKey = "gcm.message_id"
if let messageID = userInfo[gcmMessageIDKey] {
print("messageID: \(messageID)")
}
connectToFirebase()
Messaging.messaging().appDidReceiveMessage(userInfo)
if let dictString = userInfo["gcm.notification.customData"] as? String {
print("dictString \(dictString)")
if let dict = convertToDictionary(text: dictString) {
if let uid = dict["userId"] as? String,
let fullname = dict["username"] as? String,
let email = dict["email"] as? String,
let profileImageUrl = dict["profileImageurl"] as? String {
let user = User(uid: uid, fullname: fullname, email: email, profileImageurl: profileImageUrl, status: "")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let chatVC = storyboard.instantiateViewController(withIdentifier: IDENTIFIER_CHAT) as! ChatViewController
chatVC.partnerUserName = user.fullname
chatVC.partnerId = user.uid
chatVC.partnerUser = user
guard let currentVC = UIApplication.topViewController() else {
return
}
currentVC.navigationController?.pushViewController(chatVC, animated: true)
}
}
}
Extentions
extension UIApplication {
class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let navigationController = controller as? UINavigationController {
return topViewController(controller: navigationController.visibleViewController)
}
if let tabController = controller as? UITabBarController {
if let selected = tabController.selectedViewController {
return topViewController(controller: selected)
}
}
if let presented = controller?.presentedViewController {
return topViewController(controller: presented)
}
return controller
}
}
I am getting a push notification and displaying a viewcontroller based on the content of the notification.When the notification is triggered manually from postman, I get the following userInfo
[AnyHashable("google.c.a.e"): 1, AnyHashable("gcm.notification.type"): new_property, AnyHashable("gcm.notification.meta"): {"property_id":"3"}, AnyHashable("gcm.message_id"): 1570614460795417, AnyHashable("aps"): {
alert = {
body = "A new property has been published is in your area";
title = "New Property";
};
}]
// CASTING AS [String: Any]
["google.c.a.e": 1, "gcm.notification.meta": {"property_id":"3"}, "gcm.notification.type": new_property, "aps": {
alert = {
body = "A new property has been published is in your area";
title = "New Property";
};
}, "gcm.message_id": 1570614460795417]
This in turn works and displays the required screen. But when ever a user action triggers the same notification, I get this userInfo
[AnyHashable("gcm.notification.meta"): {"property_id":46}, AnyHashable("gcm.notification.type"): new_property, AnyHashable("body"): A new property has just been listed in your area by Ebenezer Kilani, AnyHashable("title"): New property Listing, AnyHashable("type"): new_property, AnyHashable("meta"): {"property_id":46}, AnyHashable("aps"): {
alert = {
body = "A new property has just been listed in your area by Ebenezer Kilani";
title = "New property Listing";
};
}, AnyHashable("gcm.message_id"): 1570550088749025, AnyHashable("google.c.a.e"): 1]
// CASTING AS [String: Any]
["meta": {"property_id":46}, "type": new_property, "title": New property Listing, "gcm.message_id": 1570550088749025, "gcm.notification.meta": {"property_id":46}, "body": A new property has just been listed in your area by Ebenezer Kilani, "aps": {
alert = {
body = "A new property has just been listed in your area by Ebenezer Kilani";
title = "New property Listing";
};
}, "google.c.a.e": 1, "gcm.notification.type": new_property]
the second payload just opens the application but never goes into the view controller I need it to. That is, it opens the home page only.
How I am getting the userInfo
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
if let usrInfo = userInfo as? [String: Any] {
extractUserInfo(userInfo: usrInfo, completion: completionHandler)
}
completionHandler()
}
func extractUserInfo(userInfo: [String: Any], completion: #escaping () -> Void) {
if let type = userInfo["gcm.notification.type"] as? String {
Storage.instance.savePush(type)
if type == "new_property" {
if let meta = userInfo["gcm.notification.meta"] as? String {
if let data = meta.data(using: .utf8) {
do {
if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] {
guard let propertyId = json["property_id"] as? String, let id = Int(propertyId) else {return}
NotificationEvent.isFromNotification.accept(true)
NotificationEvent.id.accept(id)
} else {
print("JSON is invalid")
}
} catch {
print("Exception converting: \(error)")
}
}
}
}
}
}
how I handle the push to display required Viewcontroller
class Remote {
var navigationController: UINavigationController?
let disposeBag = DisposeBag()
#discardableResult
init(navigationController: UINavigationController?) {
self.navigationController = navigationController
rxEvent()
}
func rxEvent() {
NotificationEvent.isFromNotification.asObservable().subscribe(onNext: { bool in
print("Exception converting: bool \(bool)")
if bool {
NotificationEvent.id.asObservable()
.delay(1, scheduler: MainScheduler.instance)
.subscribe(onNext: { int in
if int > 0 {
if Storage.instance.getPush() == "new_property" {
self.presentPropertyDetailVC(int)
} else if Storage.instance.getPush() == "new_rating" || Storage.instance.getPush() == "coverage_area" {
print(int)
}
}
}).disposed(by: self.disposeBag)
NotificationEvent.isFromNotification.accept(false)
}
}).disposed(by: disposeBag)
}
func presentPropertyDetailVC(_ uid: Int) {
// navigationVC.modalPresentationStyle = .formSheet
let controller = PropertyDetailVC()
controller.propertyId = uid
print("Exception converting: 11 \(controller)")
navigationController?.pushViewController(controller, animated: true)
}
}
then I instantiate Remote in my home VC
Any reason why the first payload work and the second does not and anything I could do to correct that.
This line
guard let propertyId = json["property_id"] as? String, let id = Int(propertyId) else {return}
is getting to the "return" because on the second meta 46 is an int not a string (note that it have not quotes. To fix it you can try
guard let propertyId = json["property_id"] as? String ?? String(json["property_id"] as? Int ?? 0), let id = Int(propertyId) else {return}
When my app is killed I am not receiving push notification, but is working fine with the background. After receiving notification I am generating a local notification by getting data from my realm DB. In payload content available key is 1. Please suggest me where I am going wrong, with getting fcm notification or running in the background.
here is my code -
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
let state: UIApplicationState = UIApplication.shared.applicationState
print(userInfo)
if state == .active{
let messageBody = userInfo["aps"] as! Dictionary<String,Any>
print("############# got notification")
if let message = messageBody["message"] {
let messageDict = DCUtilityClass.convertToDictionary(text: message as! String)
let _ = DCPushNotificationAPI.getNotificationResult(info: (messageDict)!)
}
} else if state == .inactive {
let messageBody = userInfo["aps"] as! Dictionary<String,Any>
print("############# got notification")
if let message = messageBody["message"] {
let messageDict = DCUtilityClass.convertToDictionary(text: message as! String)
let _ = DCPushNotificationAPI.getNotificationResult(info: (messageDict)!)
}
} else if state == .background {
let messageBody = userInfo["aps"] as! Dictionary<String,Any>
print("############# got notification")
if let message = messageBody["message"] {
let messageDict = DCUtilityClass.convertToDictionary(text: message as! String)
let _ = DCPushNotificationAPI.getNotificationResult(info: (messageDict)!)
}
}
completionHandler(UIBackgroundFetchResult.noData)
//receiveMessageMethod(recieveMessage: messageBody as! Dictionary<String, Any>)
}
and
class func triggerLocalPushNotification(title:String, body:Dictionary<String,Any>) {
//creating the notification content
let content = UNMutableNotificationContent()
//adding title, subtitle, body and badge
let messageDictModel = DCChatListHistoryModel.init().initWithUserChatDictionary(userDictionary: body)
if messageDictModel.mIsGroup{
if messageDictModel.mGroupDetailsModelArray.count == 0 {
let groupData = DCDBDataUtilityClass.getGroupInfoByConversationId(id: messageDictModel.m_id)
content.title = (groupData?.mGroupsModelArray.first?.mGroup_name)!
content.body = messageDictModel.mlatest_message
} else {
content.title = (messageDictModel.mGroupDetailsModelArray.first?.mGroup_name)!
content.body = messageDictModel.mlatest_message
}
} else {
var messageSender = ""
if messageDictModel.mMessageFrom == UserDefaults.standard.value(forKey: "user_id") as! String {
messageSender = messageDictModel.mMessage_to
} else {
messageSender = messageDictModel.mMessageFrom
}
let name = DCDBDataUtilityClass.getInfoById(id: messageSender)
content.title = (name?.mFull_name)!
content.body = messageDictModel.mlatest_message
}
//getting the notification trigger
//it will be called after 5 seconds
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.2, repeats: false)
//getting the notification request
let request = UNNotificationRequest(identifier: "iOSNotification", content: content, trigger: trigger)
//adding the notification to notification center
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
How to access any AnyHashable data in swift i have my data below , below is the log when i click the notification . When i click notif and when the data logs i want to print or get it so that i can load it on the view . it is already working and it log when i click the notif what i want is how to get it to load in the view.
what i have done
guard
let aps = userInfo[AnyHashable("aps")] as? NSDictionary,
let alert = aps["alert"] as? NSDictionary,
let body = alert["body"] as? String,
let title = alert["title"] as? String
else {
return
}
print("Title: \(title) \nBody:\(body)")
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
data
[AnyHashable("aps"): {
alert = {
body = "yuuu - 5.00";
title = "New Chore!";
};
"content-available" = 1;
}, AnyHashable("data"): {
chore = {
desc = huu;
name = yuuu;
pk = 125;
reward = "5.00";
sched = "2018-04-12T09:52:13+08:00";
};
"notification_id" = 16;
pusher = {
publishId = "pubid-01ff965a-20af-4a58-9901-89782043d832";
};
}]
You can Possibly Try:
Update for Swift 5+:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
guard let arrAPS = userInfo["aps"] as? [String: Any] else { return }
if application.applicationState == .active{
guard let arrAlert = arrAPS["alert"] as? [String:Any] else { return }
let strTitle:String = arrAlert["title"] as? String ?? ""
let strBody:String = arrAlert["body"] as? String ?? ""
let alert = UIAlertController(title: strTitle, message: strBody, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default) { action in
print("OK Action")
})
self.window?.rootViewController?.present(alert, animated: true)
} else {
guard let arrNotification = arrAPS["notification"] as? [String:Any] else { return }
guard let arrAlert = arrNotification["alert"] as? [String:Any] else { return }
let strTitle:String = arrAlert["title"] as? String ?? ""
print("Title --", strTitle)
let strBody:String = arrAlert["body"] as? String ?? ""
print("Body --", strBody)
}
}
Swift 2+ :
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
guard let dictAPS = userInfo["aps"] as? NSDictionary else { return }
if application.applicationState == .active{
let title = dictAPS.value(forKeyPath: "alert.title")
let body = dictAPS.value(forKeyPath: "alert.body")
let alert = UIAlertController(title: "\(title!)", message: "\(String(describing: body))", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default) { action in
})
self.window?.rootViewController?.present(alert, animated: true)
}else{
guard let dictNoti = dictAPS.value(forKey: "notification") as? NSDictionary else { return }
let title = dictNoti.value(forKeyPath: "alert.title")
print(title)
let body = dictNoti.value(forKeyPath: "alert.body")
print(body)
}
}
anwer : on how to load notif data when notif is tap
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)")
}
switch response.actionIdentifier {
case "action1":
print("Action First Tapped")
case "action2":
print("Action Second Tapped")
default:
break
}
// Print full message.
print(userInfo)
Messaging.messaging().appDidReceiveMessage(userInfo)
completionHandler()
}
APS data can be checked as below. You can check each keys as below to avoid crashing app if particular key is not available in notification data and handle accordingly.
if (userInfo["aps"] as? [String:Any]) != nil {
if let data = userInfo["data"] as? String{
if let desc = userInfo["desc"] as? String {
//Access variable desc here...
print(desc)
}
}
}