Why Is the Local Notification I Created with Unusernotificationcenter Not Shown in the Upper-Right Corner of My Screen

Why is the local notification I created with UNUserNotificationCenter not shown in the upper-right corner of my screen?

if you want to see notification banner while app is in foreground use below method

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// Forground notifications.
completionHandler([.alert, .sound])
}

MacOS App Local Notification Not Showing when testing with XCode

I believe that my problem here was asking permission to use UNUserNotification and then using NSUserNotification to create the notification itself, which of course I had not requested permission to use. Requesting permission is now mandatory in Catalina (and perhaps it was in earlier versions of macOS as well.)

So I replaced the generateNotification function with the following and it all works correctly.

let notificationCenter = UNUserNotificationCenter.current();
notificationCenter.getNotificationSettings
{ (settings) in
if settings.authorizationStatus == .authorized
{
//print ("Notifications Still Allowed");
// build the banner
let content = UNMutableNotificationContent();
content.title = summary ;
content.body = title ;
if sound == "YES" {content.sound = UNNotificationSound.default};
// could add .badge
// could add .userInfo

// define when banner will appear - this is set to 1 second - note you cannot set this to zero
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false);

// Create the request
let uuidString = UUID().uuidString ;
let request = UNNotificationRequest(identifier: uuidString, content: content, trigger: trigger);

// Schedule the request with the system.
notificationCenter.add(request, withCompletionHandler:
{ (error) in
if error != nil
{
// Something went wrong
}
})
//print ("Notification Generated");
}

Why is my local notifications not triggered in the foreground in iOS 10?

In reference to the following answer:
UserNotification is not showing (iOS 10)

The reason why my local notifications was not presented in the foreground is not because I "will never see the notifications in the foreground" as mentioned by the previous answer, but because I'm required to set at least the body content, and I did not set that in my code.

By setting content.body = "Some message", I can finally see the notification in the foreground while my app is running.

Display banner for NSUserNotification while app is frontmost

Your notification centre delegate and delegate method should be implemented in AppDelegate then it works. If you implement in any other class, it won't present as banner though it silently comes in notification panel.

I tried as below and its working:

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate {

func applicationDidFinishLaunching(aNotification: NSNotification) {
let notification: MyNotificationDelegate = MyNotificationDelegate()
NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self;
notification.setNotification("Hi", message: "How are you?")
}

func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool {
return true
}

func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}

}

class MyNotificationDelegate: NSObject {

func setNotification(title: String, message: String)
{
let notification: NSUserNotification = NSUserNotification()
notification.title = title
notification.informativeText = message
NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(notification)
}
}

UNUserNotificationCenter did receive response with completion handler is never called iOS10, swift 2.3

Request identifier is not the notification category.

Just add this line:

content.categoryIdentifier = identifier

Update:
Just made a simple app. Everything seems to working fine:

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

UNUserNotificationCenter.current().delegate = self

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
self.registerCategory()
self.scheduleNotification(event: "test", interval: 3)
self.scheduleNotification(event: "test2", interval: 5)
}
}

return true
}

func registerCategory() -> Void{

let callNow = UNNotificationAction(identifier: "call", title: "Call now", options: [])
let clear = UNNotificationAction(identifier: "clear", title: "Clear", options: [])
let category : UNNotificationCategory = UNNotificationCategory.init(identifier: "CALLINNOTIFICATION", actions: [callNow, clear], intentIdentifiers: [], options: [])

let center = UNUserNotificationCenter.current()
center.setNotificationCategories([category])

}

func scheduleNotification (event : String, interval: TimeInterval) {
let content = UNMutableNotificationContent()

content.title = event
content.body = "body"
content.categoryIdentifier = "CALLINNOTIFICATION"
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: interval, repeats: false)
let identifier = "id_"+event
let request = UNNotificationRequest.init(identifier: identifier, content: content, trigger: trigger)

let center = UNUserNotificationCenter.current()
center.add(request, withCompletionHandler: { (error) in
})

}

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("didReceive")
completionHandler()
}

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print("willPresent")
completionHandler([.badge, .alert, .sound])
}

}

Update 2: Rewritten in Swift 2.3

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

var window: UIWindow?

func applicationDidFinishLaunching(application: UIApplication) {
UNUserNotificationCenter.currentNotificationCenter().delegate = self
UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Badge, .Sound, .Alert]) { (granted, error) in
if granted {
self.registerCategory()
self.scheduleNotification("test", interval: 3)
self.scheduleNotification("test2", interval: 5)
}
}
}

func registerCategory() -> Void{

let callNow = UNNotificationAction(identifier: "call", title: "Call now", options: [])
let clear = UNNotificationAction(identifier: "clear", title: "Clear", options: [])
let category : UNNotificationCategory = UNNotificationCategory.init(identifier: "CALLINNOTIFICATION", actions: [callNow, clear], intentIdentifiers: [], options: [])

let center = UNUserNotificationCenter.currentNotificationCenter()
center.setNotificationCategories([category])

}

func scheduleNotification(event : String, interval: NSTimeInterval) {
let content = UNMutableNotificationContent()

content.title = event
content.body = "body"
content.categoryIdentifier = "CALLINNOTIFICATION"
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: interval, repeats: false)
let identifier = "id_"+event
let request = UNNotificationRequest.init(identifier: identifier, content: content, trigger: trigger)

let center = UNUserNotificationCenter.currentNotificationCenter()
center.addNotificationRequest(request) { (error) in

}
}

func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {

print("willPresent")
completionHandler([.Badge, .Alert, .Sound])
}

func userNotificationCenter(center: UNUserNotificationCenter, didReceiveNotificationResponse response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) {

print("didReceive")
completionHandler()
}

}

How to open VC on local notification when app is closed

So, your problem is when the app is killed or inactive and then when user tap the notification the reminder screen will show up, right?

Here's the case:
Notification shows (inactive/killed) -> tap notification -> splash -> reminder screen.

You should save your data that you want to show in notification. iOS will save any notification data in remoteNotification.

So, when user opens the app from inactive, the first thing that will be called is launchOption in AppDelegate.

Here's the example:

    if launchOptions != nil {
// get data from notificaioton when app is killed or incative
if let userInfo = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary {
// Do what you want, you can set set the trigger to move it the screen as you want, for your case is to reminder screen
}
}

How to implement LocalNotification using Objective-C?

1) When the app is closed, schedule a local notification that will fire in 24 hours

- (void)applicationDidEnterBackground:(UIApplication *)application
{
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = [[NSDate date] dateByAddingTimeInterval:60*60*24];
notification.alertBody = @"24 hours passed since last visit :(";
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

2) if the app is opened (before the local notification fires), cancel the local notification

- (void)applicationDidBecomeActive:(UIApplication *)application
{
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}

//For local Notification

first thing we need to do is register the notifications.

 // New for iOS 8 - Register the notifications
UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];

Now let’s create the notification itself

    UILocalNotification *notification = [[UILocalNotification alloc] init];
if (notification)
{
notification.fireDate = _datePicker.date;

NSDate *fireTime = [[NSDate date] addTimeInterval:10]; // adds 10 secs
notification.fireDate = fireTime;
notification.alertBody = @"Alert!";

notification.timeZone = [NSTimeZone defaultTimeZone];
notification.applicationIconBadgeNumber = 1;
notification.soundName = UILocalNotificationDefaultSoundName;
switch (_frequencySegmentedControl.selectedSegmentIndex) {
case 0:
notification.repeatInterval = NSCalendarUnitDay;
break;
case 1:
notification.repeatInterval = NSCalendarUnitWeekOfYear;
break;
case 2:

notification.repeatInterval = NSCalendarUnitYear;
break;
default:
notification.repeatInterval = 0;
break;
}
notification.alertBody = _customMessage.text;

Once we have the notification created we need to schedule it with the app.

// this will schedule the notification to fire at the fire date
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
// this will fire the notification right away, it will still also fire at the date we set
[[UIApplication sharedApplication] presentLocalNotificationNow:notification];

If we leave things the way they are now a notification will only appear on screen if the app is in the background. In order to display something when the app is in the foreground and a notification fires we need to implement a method in the app delegate.

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Notification Received" message:notification.alertBody delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alertView show];
}

We added a icon badge to our app, and this icon badge will only display when the app is in the background. Generally you want to dismiss the icon once a user has opened the app and seen the notification. We’ll need to handle this in the app delegate as well.

These two methods will take care of it.

- (void)applicationWillEnterForeground:(UIApplication *)application 
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
NSLog(@"%s", __PRETTY_FUNCTION__);
application.applicationIconBadgeNumber = 0;
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
NSLog(@"%s", __PRETTY_FUNCTION__);
application.applicationIconBadgeNumber = 0;
}


Related Topics



Leave a reply



Submit