Accessing push payload if app is inactive - ios

I have a push notification, and when app receives it, I call the following
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
if userInfo["t"] as! String == "rqst" {
print("type is help request")
if let token = NSUserDefaults.standardUserDefaults().objectForKey("authToken") {
authTokenOfHelper = token as! String
}
let storyBoard = UIStoryboard.init(name: "Main", bundle: nil)
let viewController = storyBoard.instantiateViewControllerWithIdentifier("helperMap")
let navController = UINavigationController.init(rootViewController: viewController)
self.window?.rootViewController = nil
self.window?.rootViewController = navController
self.window?.makeKeyAndVisible()
helpRequestReceived = true
}
}
this initialises storyboard.But if my app was killed by system and it is off and device recieves push, after tapping on push nothing is happened.
Seems that I have to use application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) if app is switched off
But how to access userInfo in didFinishLaunchingWithOptions ?

You can check this in didFinishLaunching using UIApplicationLaunchOptionsRemoteNotificationKey as launch options.
UIApplicationLaunchOptionsRemoteNotificationKey: Indicates that a
remote notification is available for the app to process. The value of
this key is an NSDictionary containing the payload of the remote
notification. > - alert: Either a string for the alert message or a
dictionary with two keys: body and show-view. > - badge: A number
indicating the quantity of data items to download from the provider.
This number is to be displayed on the app icon. The absence of a badge
property indicates that any number currently badging the icon should
be removed. > - sound: The name of a sound file in the app bundle to
play as an alert sound. If “default” is specified, the default sound
should be played.
You can call application:didReceiveRemoteNotification: in application:didFinishLaunchingWithOptions: manually.
Objective C
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// ...
if (launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]) {
[self application:application didReceiveRemoteNotification:launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]];
}
return YES;
}
Swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary {
self.application(application, didReceiveRemoteNotification: launchOptions![UIApplicationLaunchOptionsRemoteNotificationKey]! as! [NSObject : AnyObject])
}
return true
}

This is in Objective C but the same thing is in Swift. Put this in didFinishLaunchingWithOptions:
NSDictionary *remoteNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (remoteNotif) {
[self application:application didReceiveRemoteNotification:remoteNotif];
}
Swift:
if let remoteNotif = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary {...}

Related

How to handle Firebase push notification when iOS app is suspended/killed and user clicks on the notification?

I want to know what function should be called back or when I receive a notification while my app is suspended/killed. I am able to handle while my APP is in foreground/background however when the app is killed that's where I am not sure how and where to handle or parse my notification payload?
On open application from the notification, you will get the notification data in application:didFinishedLaunchingWithOptions method will called.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if (launchOptions != nil)
{
// opened from a push notification when the app is closed
NSDictionary* userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (userInfo != nil)
{
NSLog(#"userInfo->%#", [userInfo objectForKey:#"aps"]);
}
}
else
{
// opened app without a push notification.
}
}
Swift 5.1
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
if launchOptions != nil {
// opened from a push notification when the app is closed
let userInfo = launchOptions?[.remoteNotification] as? [AnyHashable : Any]
if userInfo != nil {
if let object = userInfo?["aps"] {
print("userInfo->\(object)")
}
}
} else {
// opened app without a push notification.
}
}

App crashes after push notification is tapped when app is killed

I am attempting to launch a specific viewController in my CustomTabBarController after receiving remote notifications. But somehow, the app always crashes when the app is killed.
Meaning to say, kill the app -> received push notifications -> tap the notifications -> app launches and crashed. This also happens when I tap the notification from the lockscreen.
I am able to execute when the app is in the background, but not when the app is killed. My code so far:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
...
if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary {
guard let rootViewController = self.window?.rootViewController as? CustomTabBarController else {
return true
}
rootViewController.selectedIndex = 1
}
return true
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
if application.applicationState == .background || application.applicationState == .inactive {
guard let rootViewController = self.window?.rootViewController as? CustomTabBarController else {
return
}
rootViewController.selectedIndex = 1
}
}
I've followed this post to check the launchOptions, but it still crash. What can I try next?
Comment these 2 lines
// window = UIWindow(frame: UIScreen.main.bounds)
// window?.makeKeyAndVisible()
as overriding the window property destroys the initialization from storyboard (makes rootVC nil) and before return true window must have one

How to handle local notification if the app is cleared from background

I just created an application to notify the task in a specific time.And It's working perfectly on time.
If I click on the notification bar it opens the app and show a alert box.
But I have problem when i cleared the application from background. Notification is working but I can't able to see the alert box when the application is opens through notification.
Please help if any one know
try this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if(userInfo)
{
[self application:application didReceiveRemoteNotification:userInfo];
}
return YES;
}
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo
{
}
swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
if let lanuchOptions = launchOptions,
let userInfo = lanuchOptions[UIApplicationLaunchOptionsKey.remoteNotification] as? [AnyHashable: Any] {
self.application(application, didReceiveRemoteNotification: userInfo)
}
return true
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
}

Swift didReceiveRemoteNotification firing while in app

Here is my code for didReceiveRemoteNotification:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
print("notification recieved: \(userInfo)")
// Pass push notification payload to the shared model
let payload: NSDictionary = userInfo as NSDictionary
if let variable = payload["variable"] as? String {
NotificationManager.SharedInstance.handleVariableNotification(variable)
}
}
The code works and properly does what I want it to when I click on the notification from outside the app.
My issue is: if I get a notification while I'm currently in the app, it still runs the code from the notification and overrides anything the user is currently doing in the app
I only want the code to run if the user clicks on the notification, not automatically if I'm already in the app.
Thanks in advance!
Wrap your code in:
if (application.applicationState != .active){}
It will check if you are currently in the app, and fires the code only if the app was inactive or in the background.
Inside your didReceiveRemoteNotification delegate method:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
switch application.applicationState {
case .active:
print("Application is open, do not override")
case .inactive, .background:
// Pass push notification payload to the shared model
let payload: NSDictionary = userInfo as NSDictionary
if let variable = payload["variable"] as? String {
NotificationManager.SharedInstance.handleVariableNotification(variable)
}
default:
print("unrecognized application state")
}
}
Also if your application is being launched via user opening a remote notification sent by your application you will need to do this inside your app delegate didFinishLaunchingWithOptions method:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Check to see if launchOptions contains any data
if launchOptions != nil {
// Check to see if the data inside launchOptions is a remote notification
if let remoteNotification = launchOptions![UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary {
// Do something with the notification
}
}
return true
}

How to get custom Push Notification value from launchOptions with swift?

I'm building an app with Swift that receives push notifications. I am sending custom values inside the JSON.
I am opening the app through the notification, so I know that I have to do this inside "didFinishLaunchingWithOptions" and read the value from "launchOptions".
How can I read those values and use them on my app.
Many thanks.
Here's what works for me in SWIFT 2 when your app is not launched. The code is not quite elegant because of the optional bindings. But it works.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// if launched from a tap on a notification
if let launchOptions = launchOptions {
if let userInfo = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] {
if let action = userInfo["action"], id = userInfo["id"] {
let rootViewController = self.window!.rootViewController as! ViewController
let _ = setTimeout(5.0, block: { () -> Void in
rootViewController.openNotification(action as! String, id: id as! String)
})
}
}
}
return true
}
In the application:didReceiveRemoteNotification:fetchCompletionHandler, The custom data is in passed on to the didReceiveRemoteNotification, which is an NSDictionary. The details that you want to retrieve is probably on the "aps" key of the userInfo.
func application(application: UIApplication, didReceiveRemoteNotification userInfo: NSDictionary!)
{
var notificationDetails: NSDictionary = userInfo.objectForKey("aps") as NSDictionary
}
When the app is not launched, you will need to get it from the application:didFinishedLaunchWithOptions,
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
if let launchOpts = launchOptions {
var notificationDetails: NSDictionary = launchOpts.objectForKey(UIApplicationLaunchOptionsRemoteNotificationKey) as NSDictionary
}
return true
}
EDIT: Remote Notification Fix syntax
This is the Oliver Zhang response which is updated for Swift 5.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// if launched from a tap on a notification
if let launchOptions = launchOptions {
if let userInfo = launchOptions[UIApplication.LaunchOptionsKey.remoteNotification] {
}
}
return true
}

Resources