I need some help in getting the inner push data.
in my app delegate file i have the following:
// Push notification received
func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {
// Print notification payload data
print("Push notification received: \(data)")
}
which results in the following:
Push notification received: [AnyHashable("aps"): {
Link = "http://www.website.com.dll?i.user8=App&id=374941&mobileOnly=true";
alert = "New survey";
}]
How would i go about in getting the value go LINK from data
thanks
You can get push data as like below.
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
let dictPayload = userInfo as NSDictionary
if let data = dictPayload.value(forKey: "aps") as? NSDictionary {
let link = data.value(forKey: "Link") as? String
print(link)
}
print("Push notification received: \(data)")
}
Related
I have a webview ios app that receives notifications and I pass a url so that when the user clicks on the notification it will open the webview to that url.
When the app is in the foreground and background it works fine. If the user gets the notification when the app is closed and not currently running then the app opens but does not go to that url
In my didReceiveRemoteNotification I detect the different states of the app but I thought that .background would work the same as not running but I guess it doesn't. How can I get the notification to open the url coming from when the app is closed?
AppDelegate.swift
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
let data = userInfo as! [String: AnyObject]
let state = UIApplication.shared.applicationState
if state == .background {
// background
//print("==== Active Running ====")
if let aps = data["aps"] {
let url = aps["url"]
viewController?.loadRequestnotification(for: url as! String)
}
}
else if state == .inactive {
// inactive
//print("==== Inactive Running ====")
if let aps = data["aps"] {
let url = aps["url"]
viewController?.loadRequestnotification(for: url as! String)
}
}
}
UPDATE
So with some help I have been able to use didFinishLaunchingWithOptions to call my webview, but the notification when pressed is still not opening to the url.
I use viewController?.loadRequestnotification(for: url as! String) in some other areas of my delegate that works fine. I am suspecting the return true might be conflicting the call.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
ConnectionManager.sharedInstance.observeReachability()
// Override point for customization after application launch.
FirebaseApp.configure()
registerForPushNotifications()
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"] as? [String : AnyObject] {
let url = object["url"]
viewController?.loadRequestnotification(for: url as! String)
}
}
}
return true
}
didReceiveRemoteNotification won't be called while app is closed.
Try this code when your app is closed to get notification data.
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"] {
let url = object["url"]")
// Now set root controller here
}
}
} else {
// opened app without a push notification.
}
}
There is one scenario like your app is not running and user click on your app's notification then following the way you can get it.
Here is code you can get it
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if let notification = launchOptions?[.remoteNotification] as? [String: Any] {
if let dictionary:NSDictionary = notification as? NSDictionary{
print("Dictionary Print in didFinishLaunching :: \(dictionary)")
}
}
}
Your app can received some notification and it is in notification center but user can not click on any notification but they will open your app as normally then following is a way, you can get all notification which is received by your app.
UNUserNotificationCenter.current().getDeliveredNotifications { (notification) in
print(notification.count)
}
This is the function that called when app receives any notification.
I have used this in my chatting app.
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
if application.applicationState == .active {
//Application is currently active and user receive the notification
} else if application.applicationState == .background {
//app is in background, but not killed
} else if application.applicationState == .inactive {
//app is transitioning from background to foreground (user taps notification), do what you need when user taps here
//Load your URL into webView from here
}
}
If app is open and you want to perform some action when notification is received
Use this method
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(UNAuthorizationOptions.alert.rawValue | UIUserNotificationType.sound.rawValue | UIUserNotificationType.badge.rawValue)
}
You can also check weather the app is open from notification or not in
AppDelegate's didFinishLaunchingWithOptions
But it is recommended to keep the this didFinishLaunchingWithOptions method light as possible.
I hope this will work for you
Running on xcode8 with swift3
Below is my code from AppDelegate.swift
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print("==== didReceiveRemoteNotification ====")
print(userInfo)
}
When I get a notification and click on it, my debug area will how like below
==== didReceiveRemoteNotification ====
[AnyHashable("type"): order, AnyHashable("aps"): {
alert = "[TestMessage]";
badge = "<null>";
category = alert;
sound = default;
}, AnyHashable("url"): http://www.google.com]
My question is how can I use userInfo to get data from AnyHashable("url") which is "www.google.com" ?
I try
print(userInfo[AnyHashable("url")])
but output in debug area is
Optional(http://www.google.com)
Try print(userInfo[AnyHashable("url")] as? String ?? "") Or you can cast it as URL
if let url = userInfo["url"] as? String {
//do whatever you need with the url
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
if let aps = userInfo["aps"] as? NSDictionary {
print(aps)
let alert = (aps.object(forKey: "alert") as? String)!
}
let url = userInfo?["url"] as? String {
print(url)
}
}
We are using kinvey business logic to push notification on postSave:
Here is what it look like if sent from engagements:
{
"aps": {
"alert": "Hello World",
"sound": "default"
},
}
The aps structure is passed as a nested object on the userInfo object that is available in the didReceiveRemoteNotification appDelegate method. You can use it with something like this in Swift:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
if let notification = userInfo["aps"] as? NSDictionary,
let alert = notification["alert"] as? String {
// do something with 'alert'
(code snippet from http://www.intertech.com/Blog/push-notifications-tutorial-for-ios-9/)
I have an app with oneSignal as push provider. I can receive push notifications, that work good. But if I try to access push payload I get nothing as didReceiveRemoteNotification not called.
I have following code
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if application.applicationState != UIApplicationState.Background {
let preBackgroundPush = !application.respondsToSelector("backgroundRefreshStatus")
let oldPushHandlerOnly = !self.respondsToSelector("application:didReceiveRemoteNotification:fetchCompletionHandler:")
var pushPayload = false
if let options = launchOptions {
pushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil
}
}
if application.respondsToSelector("registerUserNotificationSettings:") {
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
} else {
let types : UIRemoteNotificationType = [.Badge, .Alert, .Sound]
application.registerForRemoteNotificationTypes(types)
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
if userInfo["d"] as! String == "t" {
print("key was received")
}
print(userInfo)
print("PREVED")
}
Problem is that nothing prints out when I receive push. What am I doing wrong ?
try once your delegete method in this place
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
call this one
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
print("Recived: \(userInfo)")
completionHandler(.NewData)
}
Swift 4.2 - call this
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
debugPrint("Received: \(userInfo)")
completionHandler(.newData)
}
Use this code for Swift 3.0
//MARK: Push notification receive delegates
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void)
{
print("Recived: \(userInfo)")
completionHandler(.newData)
}
Hey #Alexey make sure your app provisioning file has enabled for Push Notification Service
Pretty old post but solutions can be found here in my post Push Notifications are delivered but didReceiveRemoteNotification is never called Swift or here didReceiveRemoteNotification function doesn't called with FCM notification server.
Check for this parameter: "content_available": truein your notification definition or push notification service. With underscore is how it should be set.
For some reason my didReceiveRemoteNotification is never called. I have done the following:
checklist of APNS:
Create AppId allowed with Push Notification
Create SSL certificate with valid certificate and app id
Create Provisioning profile with same certificate and make sure to add device
With Code:
Register app for push notification
Handle didRegisterForRemoteNotificationsWithDeviceToken method
Set targets> Capability> background modes> Remote Notification
Handle didReceiveRemoteNotification
Yet my function does not seem to get called. My code looks like this:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
if (application.respondsToSelector("isRegisteredForRemoteNotifications"))
{
// iOS 8 Notifications
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: (.Badge | .Sound | .Alert), categories: nil));
application.registerForRemoteNotifications()
}
else
{
// iOS < 8 Notifications
application.registerForRemoteNotificationTypes(.Badge | .Sound | .Alert)
}
return true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
var tokenString = ""
for var i = 0; i < deviceToken.length; i++ {
tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
}
apnsID = tokenString
println("******apnsID is \(apnsID)")
dToken = deviceToken
println("******dToken is \(dToken)")
NSUserDefaults.standardUserDefaults().setObject(deviceToken, forKey: "deviceToken")
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
println("***********didFailToRegisterForRemoteNotificationsWithError")
println(error)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
println("Getting notification")
var message: NSString = ""
var alert: AnyObject? = userInfo["aps"]
println(userInfo["aps"])
if((alert) != nil){
var alert = UIAlertView()
alert.title = "Title"
alert.message = "Message"
alert.addButtonWithTitle("OK")
alert.show()
}
}
add content_available:true in your request . for iOS payload data.You will get notification in didReceiveRemoteNotification. Now handle it.
As I found out having the same problem myself, in order for didReceiveRemoteNotificationto be called, the incoming notification music carry an "available_content" : true parameter with the notification payload. So in case of you sending the notification in a dictionary form , as was my case in device to device pushes, you just have to add it in the dictionary as you would specify other parameters as you would for sound or badge, also needed if you're using some sort of push service as Postman
Three steps:
Add logic here to handle incoming notification:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
// Add your logic here
completionHandler(.newData)
}
Add Background mode to capabilities in target, and ensure to check 'Remote notifications'
While sending a push notification, add "content_available" : true
This worked for me in iOS 14/Xcode 12.3.