Receive Custom Notification iOS swift 2.0 - ios

I tried to receive my custom notification from my web through parse website.
Code didReceiveRemoteNotification :
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
if application.applicationState == UIApplicationState.Inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)}
Here is the JSON i received from parse website :
[aps: {
alert = "test adirax";
sound = default; }]
It works well for me and the notification shows up. However when i tried to push data from my website, the notification can't shows/ pop up.
Here is my JSON looks like :
{"aps": {"alerts" : "test",
"links": "",
"sounds": "default"}}
I tried to print(userInfo) and the result is i get all the data like above, but there is no notif.
I guess I'm missing some code to convert the data ?
INFORMATION
For the specific information, i tried receive notification from parse.com through subscribe "channels". so it's not a local notification or else.
ADD Code Added (according to my JSON type)
if let launchOptions = launchOptions {
let userInfo = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] as? [NSObject: AnyObject]
let aps = userInfo!["aps"] as? [NSObject: AnyObject]
let alert1 = aps!["alerts"] as? String
let link1 = aps!["links"] as? String
}
And this :
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
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
print(userInfo)
print("success")
}
When i debugged one by one, its success i collect all the data, however i still missing the notification showed up ?
SOLVED PART 1
So far i managed to get the data and push the notification out, but it's only when i open the application. 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 use a local notification trick, but how to pop up the notification when i'm not using the app ?

You have to add custom informations like this:
{"aps": {"alerts" : "test",
"sound": "default"},
"name": "Steven",
"age": "32"
}
And parse it like this:
let aps = userInfo["aps"] as? [NSObject: AnyObject]
let msg = aps!["alert"] as? String
let name = userInfo["name"] as? String
print(name)
EDIT:
You have to check push notification on two functions of UIApplicationDelegate
First.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// check for push message
if let launchOptions = launchOptions {
let userInfo = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] as? [NSObject: AnyObject]
let aps = userInfo["aps"] as? [NSObject: AnyObject]
let msg = aps!["alert"] as? String
let name = userInfo["name"] as? String
print(name)
}
}
Second.
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
let aps = userInfo["aps"] as? [NSObject: AnyObject]
let msg = aps!["alert"] as? String
let name = userInfo["name"] as? String
print(name)
}

You should add your custom data to the top-level of your payload, not to the aps object.
Like this, for instance:
{
"aps": {
"alerts" : "test",
"sounds": "default"
},
"links": "",
}

Related

How to change badge number when user receive notification in background mode

func application(_ application: UIApplication, didReceiveRemoteNotification notification: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
/*
let aps = userInfo["aps"] as! [String: AnyObject]
if let count = aps["badge"] as? Int {
application.applicationIconBadgeNumber = 2
}
*/
let custom = notification["custom"] as! [String: AnyObject]
if let home = custom["a"]!["home"] as? String, home == "1" {
incrementBadgeNumberBy(badgeNumberIncrement: 1)
}
}
In General Application Badge is set from push notification payload.
Payload example:
{
“aps” : {
“badge” : 9
},
}
or
You also can set badge using
UIApplication.shared.applicationIconBadgeNumber = 3

How to handle launch options in Swift 3 when a notification is tapped? Getting syntax problems

I am trying to handle the launch option and open a specific view controller upon tapping a remote notification that I receive in swift 3. I have seen similar question, for instance here, but nothing for the new swift 3 implementation. I saw a similar question (and ) In AppDelegate.swift I have the following in didFinishLaunchingWithOptions:
var localNotif = (launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] as! String)
if localNotif {
var itemName = (localNotif.userInfo!["aps"] as! String)
print("Custom: \(itemName)")
}
else {
print("//////////////////////////")
}
but Xcode is giving me this error:
Type '[NSObject: AnyObject]?' has no subscript members
I also tried this:
if let launchOptions = launchOptions {
var notificationPayload: NSDictionary = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] as NSDictionary!
}
and I get this error:
error: ambiguous reference to member 'subscript'
I got similar errors wherever I had previously used similar code to get a value from a dictionary by the key and I had to replace the codes and basically safely unwrap the dictionary first. But that doesn't seem to work here. Any help would be appreciated. Thanks.
Apple made plenty of changes in Swift 3 and this one of them.
Edit: This works for Swift 4 as well.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//Launched from push notification
let remoteNotif = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [String: Any]
if remoteNotif != nil {
let aps = remoteNotif!["aps"] as? [String:AnyObject]
NSLog("\n Custom: \(String(describing: aps))")
}
else {
NSLog("//////////////////////////Normal launch")
}
}
Swift 5:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//Launched from push notification
guard let options = launchOptions,
let remoteNotif = options[UIApplication.LaunchOptionsKey.remoteNotification] as? [String: Any]
else {
return
}
let aps = remoteNotif["aps"] as? [String: Any]
NSLog("\n Custom: \(String(describing: aps))")
handleRemoteNotification(remoteNotif)
}
And for more on LaunchOptionsKey read Apple's documentation.
So it turned out the whole method signature has changed and when I implemented the new signature things worked just fine. Below is the code.
new didFinishLaunchingWithOptions method:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
//and then
if launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] != nil {
// Do what you want to happen when a remote notification is tapped.
}
}
Hope this helps.
Swift 4
// Check if launched from the remote notification and application is close
if let remoteNotification = launchOptions?[.remoteNotification] as? [AnyHashable : Any] {
// Do what you want to happen when a remote notification is tapped.
let aps = remoteNotification["aps" as String] as? [String:AnyObject]
let apsString = String(describing: aps)
debugPrint("\n last incoming aps: \(apsString)")
}
swift 3:
if let notification = launchOptions?[.localNotification] as? NSDictionary{
#if DEBUG
print("iOS9 didFinishLaunchingWithOptions notification\n \(notification)")
#endif
if let remoteNotif = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [String: Any] {
if let notification = remoteNotif["aps"] as? [AnyHashable : Any] {
//handle PN
}
}

Why not able to handle APNS Push notification and Local notification?

I am working with Push notification and local notification also but in foreground notification working fine but when terminate app in this condition i can not able to redirect specific view when tap on notifications.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Check if launched from notification
// 1
if let notification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? [String: AnyObject] {
// 2
let aps = notification["aps"] as! [String: AnyObject]
//Redirect to notification view
handlePushMessage(aps)
}else if let notification = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as? [String: AnyObject] {
// 2
self.postData = notification["aps"] as! [String: AnyObject]
//Redirect to notification view
didTapNotification()
}else{
//Session
//Redirect to Main view
checkUserSession()
}
return true
}
I am facing this facing this problem from both APNS notification and local notification when app is Inactive or terminate.Please help me fro find the solution.
How about you try in didReceiveRemoteNotification function?
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
if(application.applicationState == UIApplicationStateBackground){
}else if(application.applicationState == UIApplicationStateInactive){
}
}
try this code, you can modify it according to you requirement. if you have any problem understanding this logic let me know. didReceiveRemoteNotification with completionHandler works both in background and in foreground. Don't forget to do appropriate changes in plist to support background fetch and background notification.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
application.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
if let notification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? [String: AnyObject] {
notificationDataDict = notification;
}
return true
}
func handleRemoteNotificationWithUserInfo(application:UIApplication, userInfo:NSDictionary){
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
print(userInfo)
if application.applicationState != .Inactive{
notificationDataDict = userInfo;
if let navigationController = self.window?.rootViewController as? UINavigationController{
if application.applicationState == .Active{
if application.backgroundRefreshStatus == .Available{
completionHandler(.NewData)
self.handleRemoteNotificationWithUserInfo(application, userInfo: userInfo)
}
else
{
completionHandler(.NoData)
}
}
else{
completionHandler(.NewData)
self.handleRemoteNotificationWithUserInfo(application, userInfo: userInfo)
}
}
}
}
Finally i got the solution for Manage APNS Push notification and Local notification, its working fine now.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)
//Register here For Notification
if #available(iOS 9, *) {
let notificationTypes: UIUserNotificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]
let pushNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)
application.registerUserNotificationSettings(pushNotificationSettings)
application.registerForRemoteNotifications()
}else{
UIApplication.sharedApplication().registerUserNotificationSettings(
UIUserNotificationSettings(forTypes: .Alert, categories: nil))
application.registerForRemoteNotifications()
}
dispatch_async(dispatch_get_main_queue()) {
// Check if launched from notification
// 1
if let notification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? [String: AnyObject] {
// 2
let aps = notification["aps"] as! [String: AnyObject]
handlePushMessage(aps)
}else if let notification = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification {
// 2
self.postData = notification.userInfo as! [String: AnyObject]
didTapNotification()
}else{
//Session
checkUserSession()
}
}
}

Why the didReceiveRemoteNotification is not being called?

I'm trying to create a subscription using CloudKit to fires every time a record is created. I have successfully created the subscription, I can see it in dashboard, but I've noticed that the print I have in didReceiveRemoteNotification was never printed!
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
print("oioioioioi")
let viewController: CurrentEventController = self.window?.rootViewController as! CurrentEventController
if let userInfo = userInfo as? [String: NSObject] {
let notification: CKNotification = CKNotification(fromRemoteNotificationDictionary: userInfo)
if (notification.notificationType == CKNotificationType.Query) {
let queryNotification = notification as! CKQueryNotification
let recordID = queryNotification.recordID
viewController.fetchRecord(recordID!)
}
}
}
Thanks for any help!

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.

Resources