How can I get the json string value from a Push Notification? - ios

I need to store the last alert json string value coming from a Push Notification.
Using "aps: \(userInfo["aps"]!)" returns the whole json:
aps: {
alert = "last alert message";
}
but I only need "last alert message".
This is my code:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler completionHandler: (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.
dUserInfo = userInfo
print("aps: \(userInfo["aps"]!)")
NSUserDefaults.standardUserDefaults().setObject(dUserInfo, forKey: "last_push")
NSUserDefaults.standardUserDefaults().synchronize()
}
How can I get the message properly?

Try this:
if let aps = userInfo["aps"] as? [String: AnyObject] {
if let alert = aps["alert"] as? String {
NSUserDefaults.standardUserDefaults().setObject(alert, forKey: "last_push")
}
}

Related

getting push data in swift 3

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)")
}

What would the received push schema would look like on IOS

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/)

GCM iOS can't convert message object received

I m using GCM for iOS and I receive the message that I push but the message look like this object :
[aps: {
alert = {
body = "great match!";
title = "Portugal vs. Denmark";
};
}, gcm.message_id: 0:1464264430528872......]
Here is the entire function called when I receive a message :
func application( application: UIApplication,
didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) {
print("Notification received: \(userInfo)")
print(userInfo)
// This works only if the app started the GCM service
GCMService.sharedInstance().appDidReceiveMessage(userInfo);
// Handle the received message
// Invoke the completion handler passing the appropriate UIBackgroundFetchResult value
// [START_EXCLUDE]
NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil,
userInfo: userInfo)
handler(UIBackgroundFetchResult.NoData);
// [END_EXCLUDE]
}
I don't find how to get the alert body and alert title how can I do that ?
userInfo is a dictionary of type [NSObject : AnyObject]. To access the values, use subscripting.
The "aps" key contains a dictionary which contains a dictionary, so, for example, you could do:
if let aps = userInfo["aps"] as? [String:[String:String]],
alert = aps["alert"],
body = alert["body"],
title = alert["title"] {
print(title)
print(body)
}

UILocalNotification didn't showed up

This is my ReceiveRemoteNotification code.
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
if application.applicationState == UIApplicationState.Inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
}
let notifiAlert = UIAlertView()
let aps = userInfo["aps"] as? [NSObject: AnyObject]
let alert1 = aps!["alerts"] as? String
let link1 = aps!["links"] as? String
notifiAlert.title = alert1!
notifiAlert.message = link1
notifiAlert.addButtonWithTitle("OK")
notifiAlert.show()
print(userInfo)
print("success")
}
i tried to receive JSON data from my web, my JSON looks like :
{"aps":{"alerts":"3","links":"","sounds":"default"}}
I did receive the Json data and turn the data to the view. with this code :
let aps = userInfo["aps"] as? [NSObject: AnyObject]
let alert1 = aps!["alerts"] as? String
let link1 = aps!["links"] as? String
notifiAlert.title = alert1!
notifiAlert.message = link1
notifiAlert.addButtonWithTitle("OK")
notifiAlert.show()
print(userInfo)
print("success")
}
However i only receive when i was using the application, but if i'm not using, i can't receive the notification. but my phone was vibrate or make sound, but no message.
Am i missing something right here ? thanks !
Added Here is my full code http://pastebin.com/mkFiq6Cs
EDIT
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
if application.applicationState == UIApplicationState.Inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
}
let aps = userInfo["aps"] as? [NSObject: AnyObject]
let alert1 = aps!["alerts"] as? String
let link1 = aps!["links"] as? String
notifiAlert.title = alert1!
notifiAlert.message = link1
notifiAlert.addButtonWithTitle("OK")
notifiAlert.show()
print(userInfo)
print("success")
}
So i have to add this code :
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
if let userInfo = notification.userInfo {
let aps = userInfo["aps"] as? [NSObject: AnyObject]
let alert2 = aps!["alerts"] as? String
let link2 = aps!["links"] as? String
print("didReceiveLocalNotification: \(aps)")
print("didReceiveLocalNotification: \(alert2)")
print("didReceiveLocalNotification: \(link2)")
}
}
And this at didFinishLaunchingOption :
if let options = launchOptions {
if let notification = options[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification {
if let userInfo = notification.userInfo {
let customField1 = userInfo["CustomField1"] as! String
// do something neat here
}
}
}
SOLVED
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
PFPush.handlePush(userInfo)
if application.applicationState == UIApplicationState.Inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
}
let notifiAlert = UIAlertView()
if let aps = userInfo["aps"] as? [NSObject: AnyObject],
let alert1 = aps["alert"] as? String,
let content1 = aps["content-available"] as? String,
let link1 = userInfo["links"] as? String {
notifiAlert.title = alert1
notifiAlert.message = link1
notifiAlert.addButtonWithTitle("OK")
notifiAlert.show()
}
print(userInfo)
print("success")
completionHandler(UIBackgroundFetchResult.NewData)
}
This works perfectly. ! Thanks to #tskulbru
This is because application(_:didReceiveRemoteNotification:) is only called when the application is active. It cant handle app-inactive/background remote notifications.
If the app is not running when a remote notification arrives, the method launches the app and provides the appropriate information in the launch options dictionary. The app does not call this method to handle that remote notification. Instead, your implementation of the application:willFinishLaunchingWithOptions: or application:didFinishLaunchingWithOptions: method needs to get the remote notification payload data and respond appropriately.
Source: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplicationDelegate_Protocol/index.html?hl=ar#//apple_ref/occ/intfm/UIApplicationDelegate/application:didReceiveRemoteNotification:
As said above, application:didReceiveRemoteNotification needs to have additional implementation if it should be able to handle background notifications.
If you instead want just one method to handle all the goodies for you, and don't have a bunch of different methods to implement basically the same thing, Apple has provided a method called application:didReceiveRemoteNotification:fetchCompletionHandler: to handle all this for you.
You need to implement the application:didReceiveRemoteNotification:fetchCompletionHandler: method instead of this one to handle background notifications. This handles background tasks, and you can then call the completionHandler with the appropiate enum when you are finished (.NoData / .NewData / .Failed).
If you want to have a local notification presented when you receive a remote notification while the application is active you will need to create that in the aforementioned method. And if you want to display an alertview if the application is active, you also need to handle the two scenarios in that method. My recommendation is to switch to application:didReceiveRemoteNotification:fetchCompletionHandler: instead and implement everything there.
So in your case, I would do something like this:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
PFPush.handlePush(userInfo)
if application.applicationState == UIApplicationState.Inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
} else {
let notifiAlert = UIAlertView()
if let aps = userInfo["aps"] as? [NSObject: AnyObject],
let alert1 = aps["alerts"] as? String,
let link1 = aps["links"] as? String {
notifiAlert.title = alert1
notifiAlert.message = link1
notifiAlert.addButtonWithTitle("OK")
notifiAlert.show()
}
print(userInfo)
print("success")
}
completionHandler(UIBackgroundFetchResult.NewData)
}
I've not tested the code but it should be something like that without too many changes. I havent used Parse so I don't know exactly what PFPush.handlePush(userInfo) does, you need to check the documentation for that.
Looks like your apns payload is wrong too. See https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/TheNotificationPayload.html#//apple_ref/doc/uid/TP40008194-CH107-SW1
In your case:
{"aps":{"alert":"alert content","sound":"default", "content-available": 1}, "links":""}
You had plural form instead of single form. Look at the url I gave for the allowed keys. The links key doesn't exist in aps dictionary, which mean its a custom key and needs to be placed outside the dictionary.
Note that this is the standard push notification way and might not be correct when using Parse.

Direct link to browser with Notification

This is a simple logic, but i can't figure it out.
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
PFPush.handlePush(userInfo)
if application.applicationState == UIApplicationState.Inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
}
if let aps = userInfo["aps"] as? [NSObject: AnyObject],
let alert1 = aps["alert"] as? String,
let content1 = aps["content-available"] as? String,
let link1 = aps["links"] as? String {
if link1 == "" {
//Ok pressed do nothing
}else{
// after OK pressed. jump to page "example" http://www.google.com
}
}
completionHandler(UIBackgroundFetchResult.NewData)
}
I have a push from my web. It contain 2 type of push :
I push notify without link
I push with link inside. (if i press the notify ill jump to
the page example : http://www.google.com)
if without link, "link1" will be empty and just showed up message. after that nothing.
However if i push with a link, How can i jump to the browser after i pressed the ok button ?
Added Full code if you want to see http://pastebin.com/cFYqLqs7
ASK Should i use Deep linking in this case ? because the link can change depend on what i push.

Resources