How to receive in - app push notifications when app is open? - ios

I'm currently using a library called "whisper" that is supposed to help with showing in-app push notifications Whisper Link
In my "didReceiveRemoteNotification" I have it set up as follows:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
if application.applicationState == .Active {
let navigationController = self.window!.rootViewController as! UINavigationController
if let aps = userInfo["aps"] as? NSDictionary {
if let alert = aps["alert"] as? NSDictionary {
if let title = alert["title"] as? NSString {
if let body = alert["body"] as? NSString {
let announcement = Announcement(title: title as! String, subtitle: body as! String, image: UIImage(named: "HolyGrailLogo-58"))
Shout(announcement, to: navigationController)
}
}
}
}
// Show and hide a message after delay
}
}
For some strange reason I'm not receiving any push notifications, not sure why.

Check in your device settings that your app is able to receive remote notification.
Put a print statement after this method func application(application: UIApplication, didReceiveRemoteNotification.
If it is not printing then issue is with your library.
.Active check is not required. When app is in background this method will not execute.

Related

IOS handle push notification when app is closed

I want to push UIViewController when notification is clicked and app is closed
following is my code in didReceiveRemoteNotification
if application.applicationState == .inactive || application.applicationState == .background {
DeeplinkHandler.handleNotification(userNotification: userNotification)
completionHandler(UIBackgroundFetchResult.newData)
}
following is code to handle notification deep link
class func handleNotification(userNotification : UserNotification?){
let appDelegate = UIApplication.shared.delegate as! AppDelegate
var navigationVC = UINavigationController()
if let tabBarVC = appDelegate.window?.rootViewController as? UITabBarController {
if let navVC = tabBarVC.viewControllers?[tabBarVC.selectedIndex] as? UINavigationController {
navigationVC = navVC
}
else {
tabBarVC.selectedIndex = 0
navigationVC = tabBarVC.viewControllers?[0] as! UINavigationController
}
}
// let navigationVC = appDelegate.window?.rootViewController as! UINavigationController
switch userNotification?.type ?? "" {
case DeeplinkHandler.NOTIF_TYPE_WEBVIEW:
let appWebView = AppStrings.appStoryBoard.instantiateViewController(withIdentifier: "webPageViewControllerID") as! WebPageViewController
appWebView.url = userNotification?.url ?? ""
navigationVC.pushViewController(appWebView, animated: true)
//case DeeplinkHandler.NOTIF_TYPE_PAGE_ID:
//case DeeplinkHandler.NOTIF_TYPE_FLIGHT_STATUS:
default:
let appWebView = AppStrings.appStoryBoard.instantiateViewController(withIdentifier: "notificationViewControllerID") as! NotificationViewController
//appWebView.url = userNotification?.url ?? ""
navigationVC.pushViewController(appWebView, animated: true)
}
}
But notification is click is causing a crash when clicked on notification when app is closed.
How to handle this?
tried following code in didFinishLaunchingWithOptions
var notification: [AnyHashable: Any]? = (launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] as? [AnyHashable: Any])
if let notification = notification {
print("app received notification from remote\(notification)")
var userNotification : UserNotification?
if notification is [String : Any] {
userNotification = createNSaveNotification(notification)
DeeplinkHandler.handleNotification(userNotification: userNotification)
}
}
else {
print("app did not receive notification")
}
this is also crashing app on notification click when app is closed
when app close, you have to check notification in method
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary<UIApplicationLaunchOptionsKey, id> *)launchOptions;
and check data in launchOptions

IOS app won't display push notification when in background. Swift

Ok so my push notification work like a charm when the app is running in the foreground. But when ever I enter into the background, the app never receives the push notification. Its like the notification falls on deaf ears.
So this is what happening. When the app is first started, I can received notification. When I close and reopen the app I can receive notification. But when the app is closed in the background I cannot receive notification. I print off when the app goes into the background and when the app becomes active so I know that its not closing I think. Because its printing that its going into the background, so it should be running.
So this is what I have for the app deligate class:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//OTHER THINGS
//Open the Push note page
if launchOptions != nil
{
print(launchOptions)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier(myPage)
self.window?.rootViewController = vc
}
//handel push note if app is closed
//Sends it to the regular handler for push notifcaiton
//didrecivepushnotificaiton
if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary
{
print("Got A Push Note when I was closed")
self.application(application, didReceiveRemoteNotification: remoteNotification as [NSObject : AnyObject])
}
}
func application( application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken
deviceToken: NSData ) {
print("DEVICE TOKEN = \(deviceToken)")
//convert the device token into a string
let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
var token = ""
for i in 0..<deviceToken.length {
token += String(format: "%02.2hhx", arguments: [tokenChars[i]])
}
print("token: " + token)
//store the user device token for apns push notification
loginInformation.setObject(token, forKey: "token")
self.loginInformation.synchronize()
}
// [START ack_message_reception]
func application( application: UIApplication,
didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
print("Recived Push Notificaion")
var myMess :String = ""
var url : String = ""
var myTitle : String = ""
if var alertDict = userInfo["aps"] as? Dictionary<String, String> {
print("Alert Dict")
print(alertDict)
url = alertDict["url"]!
myMess = alertDict["alert"]!
myTitle = alertDict["mytitle"]!
//store the url for the push control view
loginInformation.setObject(url, forKey: "URL")
loginInformation.setObject(myMess, forKey: "Message")
loginInformation.setObject(myTitle, forKey: "Title")
self.loginInformation.synchronize()
}else{print("No go")}
application.applicationIconBadgeNumber = 0
//post notification.
NSNotificationCenter.defaultCenter().postNotificationName("PushReceived", object: nil, userInfo: userInfo)
if myTitle == ""
{
myTitle = “New Title“
}
if myMess == ""
{
myMess = “All Hail Gus“
}
let alert = UIAlertController(title: myTitle, message: myMess, preferredStyle: UIAlertControllerStyle.Alert)
//Close Button
alert.addAction(UIAlertAction(title: "次回", style: UIAlertActionStyle.Default, handler: nil))
self.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
}
func registrationHandler(registrationToken: String!, error: NSError!) {
}
// [START receive_apns_token_error]
func application( application: UIApplication, didFailToRegisterForRemoteNotificationsWithError
error: NSError ) {
print(error)
}
I think I have all the right setting on this too. But I am not too sure now. The push notifications did work but I made a lot of changes and haven't tested them in a while.
And this is an example of the payload
{"aps":{"alert":"Gus Message.","badge":"1", "url":"https://www.gus.com","mytitle":"Gus Title"}}
To fully implement APNS servie, u have to handle three cases:
inactive
foreground
background
the inactive mode should be handled in didFinishLaunchingWithOptions method
//receive apns when app in inactive mode, remaining message hint display task could be sum up by the code in applicationwillenterforeground
if let options = launchOptions {
if options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil {
let userInfo: NSDictionary = options[UIApplicationLaunchOptionsRemoteNotificationKey] as! NSDictionary
let apsInfo: NSDictionary = userInfo["aps"] as! NSDictionary
//parse notification body message ...
NSNotificationCenter.defaultCenter().postNotificationName(APP_NOTIF_RECEIVE_REMOTE_NOTIF, object: userInfo)
APService.handleRemoteNotification(userInfo as! [NSObject : AnyObject])
//Update badge number
let badgeIndex = apsInfo["badge"] as! Int
UIApplication.sharedApplication().applicationIconBadgeNumber = badgeIndex
}
}
} else if options[UIApplicationLaunchOptionsURLKey] != nil {
if let url = launchOptions?[UIApplicationLaunchOptionsURLKey] as? NSURL {
print(url)
}
}
}
the remaining two cases should be handle in didReceiveRemoteNotification method
//receive apns when app in background mode
let apsInfo: NSDictionary = userInfo["aps"] as! NSDictionary
if UIApplication.sharedApplication().applicationState != UIApplicationState.Active{
//TODO: temporary method, need further update
//judge notification type
if let _ = userInfo["inviterName"] as? String {
//notification for group invite
}else{
//Update badge number
if let badgeInt = apsInfo["badge"] as? Int {
UIApplication.sharedApplication().applicationIconBadgeNumber = badgeInt > 0 ? badgeInt: 1
}else{
UIApplication.sharedApplication().applicationIconBadgeNumber = 1
}
//turn on trigger to enable message hint btn on recorder vc when it appear
NSUserDefaults.standardUserDefaults().setBool(true, forKey: REMOTE_NOTIF_REMAINING)
}
}
//receive apns when app in forground mode
else{
//TODO: temporary method, need further update
//judge notification type
if let _ = userInfo["inviterName"] as? String {
//notification for group invite
NSNotificationCenter.defaultCenter().postNotificationName(APP_NOTIF_RECEIVE_GROUP_NOTIF, object:nil)
}else{
//notificate recorder vc to display message hint directly
NSNotificationCenter.defaultCenter().postNotificationName(APP_NOTIF_RECEIVE_REMOTE_NOTIF, object: userInfo)
}
}
APService.handleRemoteNotification(userInfo)
completionHandler(UIBackgroundFetchResult.NewData)

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!

Swift receiving push notifications (Parse) when the app is not running

I am building an iOS app using Swift and I want to receive push notifications (Parse) when someone has mentioned me.
I have used a navigation controller as the initial view controller and first view controller is the sign in view controller. In this view controller there is an if statement which checks whether the user in already logged in or not. If the user is already logged in then the app jumps automatically to the main screen.
If the sign in is successful, the app jumps to main screen.
My notifications work fine in the following cases:
The app is running
The app is running on the background, and when I tap on the notification bar, the app jumps on the notification screen
My notifications do not work in the following cases:
The app is running on the background, when I tap the icon with the badge (i.e. 1) it shows the main screen and not the notification screen
The app is not running at all, and I am running it through the notification. In this case the app is stacked on the sign in screen and it is not responding. I think that the problem is because it waits for the user to be signed in.
I do not know whether there is an issue in the AppDelegate.swift file. I have followed the Parse documentation as well as the Starter project for Parse in order to code it.
Following are the methods from the AppDelegate.swift
Method application: didFinishLaunchingWithOptions
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if let notificationPayload = launchOptions? [UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary {
let meetingId = notificationPayload["meetingId"] as? String
let targetMeeting = PFObject(withoutDataWithClassName: "Meeting", objectId: meetingId)
targetMeeting.fetchIfNeededInBackgroundWithBlock({ (object, error) -> Void in
if error == nil {
let meetingToRespond = Meeting(id: targetMeeting.objectId!, name: targetMeeting["name"] as! String, location: CLLocationCoordinate2DMake((targetMeeting["location"]?.latitude)!, (targetMeeting["location"]?.longitude)!), day: targetMeeting["dayTime"] as! NSDate)
var rootViewController = self.window?.rootViewController as! UINavigationController
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let notificationScreen = mainStoryboard.instantiateViewControllerWithIdentifier("screenForNotification") as! MeetingToRespondViewController
notificationScreen.meeting = meetingToRespond
rootViewController.pushViewController(notificationScreen, animated: true)
}
})
}
// Enable storing and querying data from Local Datastore.
// Remove this line if you don't want to use Local Datastore features or want to use cachePolicy.
Parse.enableLocalDatastore()
Parse.setApplicationId("###",
clientKey: "###")
PFFacebookUtils.initializeFacebookWithApplicationLaunchOptions(launchOptions)
PFUser.enableAutomaticUser()
let defaultACL = PFACL();
// If you would like all objects to be private by default, remove this line.
defaultACL.setPublicReadAccess(true)
PFACL.setDefaultACL(defaultACL, withAccessForCurrentUser:true)
if application.applicationState != UIApplicationState.Background {
// Track an app open here if we launch with a push, unless
// "content_available" was used to trigger a background push (introduced in iOS 7).
// In that case, we skip tracking here to avoid double counting the app-open.
let oldPushHandlerOnly = !self.respondsToSelector(Selector("application:didReceiveRemoteNotification:fetchCompletionHandler:"))
let noPushPayload: AnyObject? = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey]
if oldPushHandlerOnly || noPushPayload != nil {
PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
}
}
if application.respondsToSelector("registerUserNotificationSettings:") {
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
} else {
let types: UIRemoteNotificationType = [UIRemoteNotificationType.Badge, UIRemoteNotificationType.Alert, UIRemoteNotificationType.Sound]
application.registerForRemoteNotificationTypes(types)
}
return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
}
Method application: didRegisterForRemoteNotificationsWithDeviceToken
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.saveInBackground()
}
Method application: didReceiveRemoteNotification
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
if application.applicationState == .Inactive {
// The application was just brought from the background to the foreground, so we consider the app as having been "opened by a push notification."
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
}
}
Method application:didReceiveRemoteNotification:fetchCompletionHandler
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
if application.applicationState == .Inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
}
if let meetingId: String = userInfo["meetingId"] as? String {
let targetMeeting = PFObject(withoutDataWithClassName: "Meeting", objectId: meetingId)
targetMeeting.fetchIfNeededInBackgroundWithBlock({ (object, error) -> Void in
// Show meeting to respond view controller
if error != nil {
completionHandler(UIBackgroundFetchResult.Failed)
} else if PFUser.currentUser() != nil {
// Get the meeting
let meetingToRespond = Meeting(id: targetMeeting.objectId!, name: targetMeeting["name"] as! String, location: CLLocationCoordinate2DMake((targetMeeting["location"]?.latitude)!, (targetMeeting["location"]?.longitude)!), day: targetMeeting["dayTime"] as! NSDate)
var rootViewController = self.window?.rootViewController as! UINavigationController
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let notificationScreen = mainStoryboard.instantiateViewControllerWithIdentifier("screenForNotification") as! MeetingToRespondViewController
notificationScreen.meeting = meetingToRespond
rootViewController.pushViewController(notificationScreen, animated: true)
completionHandler(UIBackgroundFetchResult.NewData)
} else {
completionHandler(UIBackgroundFetchResult.NoData)
}
})
}
completionHandler(UIBackgroundFetchResult.NoData)
}
Method applicationDidBecomeActive: application
func applicationDidBecomeActive(application: UIApplication) {
// Clear the badge
let currentInstallation = PFInstallation.currentInstallation()
if currentInstallation.badge != 0 {
currentInstallation.badge = 0
currentInstallation.saveEventually()
}
FBSDKAppEvents.activateApp()
}
Thank you in advance!!! :D :) ;)

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