UILocalNotifcation not fired in swift 2.0 - ios

I am working Push notification and i have done all steps to setup push notification.
i can able to receive notification when application in background but when application in foreground its landing on didReceiveRemoteNotification but its not firing.
here my code in AppDelegate.swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let notificationSettings = UIUserNotificationSettings(forTypes: [.Badge, .Alert, .Sound], categories: nil)
application.registerUserNotificationSettings(notificationSettings)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
if application.applicationState == UIApplicationState.Active {
let localNotification = UILocalNotification()
let date = NSDate(timeIntervalSinceNow: 10)
localNotification.fireDate = date
let timeZone = NSTimeZone.localTimeZone()
localNotification.timeZone = timeZone
localNotification.alertBody = "Sample Notification Body"
localNotification.userInfo = userInfo
print(localNotification)
localNotification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
}
What mistake i am doing ??
Thanks in advance

What I suspect is, you're trying to show the remote notification when the app is active using local notification.
Well, either its local notification or remote, you can't see any UI alert when the app is active, instead the delegate methods for local or remote notification are called accordingly.
However iOS 10 adds the ability to view it inside the app. Here's the discussion: https://stackoverflow.com/a/37844312/593709
For showing any alert on pre-iOS-10, while your app is active, you need to use UIAlertController or some other implementation like MPNotificationView.

When the application is in Foreground and running, it does not show notification banner. Banner alert is only shown when Application is either in background(inactive) or is not running at all. The delegate method
application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void)
is called for Remote(Push) Notification and
application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification)
is called for local notification.
You can use any 3rd party library bryx-inc/BRYXBanner to show a banner for your notification alert message . The delegate method didReceiveRemoteNotification can be used to update badge icon and show message in banner view.

Related

IOS doesn't receive first notification in background

IOS 13.7 IPhone Xr, Xcode Version 11.7 (11E801a)
I edited app scheme and set launch mode to "Wait for the executable to be launched". I run app, and send a simple notification on my device.
this notification:
{
"aps":{
"content-available":1
}
}
in xcode status changed from "Waiting to attach to test on iPhone" to "Running test on iPhone", but the notification wasn't received.
i try catch notification in this method:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void)
Next notification I receive successfully. This case can be repeated after application reload.
Can you help me find out why I don't receive the first notification
Please try this payload :
{"aps":{"alert":"","content-available":1}}
If your app wasn’t running, the push notification is passed to your AppDelegate in the launchOptions
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
...
let notificationOption = launchOptions?[.remoteNotification]
if let notification = notificationOption as? [String:AnyObject]{
// received notification
}
...
}

Remote notification when app is terminated

I am new to iOS and Swift. I am implementing remote notification in my app. Everything works fine when the app is active or in the background. But my notification does not show up when the app is terminated. All I am getting is the alert sound of the notification.
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
if #available(iOS 10.0, *){
}else{
let notification = UILocalNotification()
notification.alertTitle = "my Title"
notification.alertBody = "My Message"
notification.category = "customCategory"
notification.soundName = UILocalNotificationDefaultSoundName
application.scheduleLocalNotification(notification)
}
}
Below AppDelegate method will be called When you receive a notification and application is in killed state
didFinishLaunchingWithOptions
So you should handle it properly from here when app is in killed state.
Below code helps to identify the Remote/push or Local notification in didFinishLaunchingWithOptions method:
if let launchOpts = launchOptions as [UIApplicationLaunchOptionsKey: Any]? {
if let notificationPayload = launchOpts[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary {
//Handle push notification here
}
else if let notification = (launchOpts as NSDictionary).object(forKey: "UIApplicationLaunchOptionsLocalNotificationKey") as? UILocalNotification {
//Handle local notification here
}

Local notifications stopped working, can't figure out why

I got local notifications working for my iOS project some time last year before putting it aside, but when I came back a few weeks ago I noticed that they no longer worked. I've dug around for a few days and I'm completely stumped. The badge still updates properly with a background fetch, but the notification alert is no longer sent. Here's a minimal setup of what I have for testing.
AppDelegate:
func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
application.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Badge, .Alert], categories: nil))
return true
}
func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
let localNotification = UILocalNotification()
localNotification.alertAction = "Message"
application.presentLocalNotificationNow(localNotification)
completionHandler(.NoData)
}
Things I've tried:
Uninstalling/reinstalling the app (device and simulators)
Changing the Bundle identifier
Disabling/re-enabling background fetch capability
Present delayed local notification by adding the fireDate attribute
Tried willFinishLaunchingWithOptions and didFinishLaunchingWithOptions
I've debugged it and am 100% certain that performFetchWithCompletionHandler executes when I simulate background fetch and that presentLocalNotificationNow is called
Setup:
Xcode 7.3.1 (started on previous release, probably 6.x.x)
Swift 2.2 (started the project on 2.1 and was functional)
iOS 9 (started the project on 8 and was functional)
Did something change in the API that I missed, or is there some error in what I'm doing? Thanks for any help!
UILocalNotification requires that alertBody be set in order to display. So having the following works:
func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
let localNotification = UILocalNotification()
localNotification.alertBody = "You have a notification"
localNotification.alertAction = "Message"
application.presentLocalNotificationNow(localNotification)
completionHandler(.NoData)
}

didReceiveRemoteNotification not called Swift

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.

Catch push notification text on lock screen

How can I get the push notification text when the app does not run or in lock screen?
I did try:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
println(userInfo)
// or just
println("something")
}
But it doesn't print me anything. Is it wrong function???
didReceiveRemoteNotification function only called this condition.
while app will running and app in foreground.(alert not showing)
if app in background and click notification on home screen
if app not run in device didReceiveRemoteNotification function not called,
in this case user click notification in home screen, we identify app launched by notification or not in didFinishLaunchingWithOptions
UILocalNotification *localNotif =[launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
you get userinfo data in localNotif.userinfo
Try in Swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
var userinfo : NSDictionary =launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
print(launchOptions);
return true
}

Resources