Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Local Notification doesn't get triggered

I am coding in Swift 3 and I am simply trying to send a notification now without any delays or intervals. However the notification never gets triggered. Here's my code..

The ViewController code

import UserNotifications

class HomeViewController: UIViewController{
    var isGrantedNotificationAccess:Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()

        UNUserNotificationCenter.current().requestAuthorization(
            options: [.alert,.sound,.badge],
            completionHandler: { (granted,error) in
                self.isGrantedNotificationAccess = granted
        })

        if isGrantedNotificationAccess{
            triggerNotification()
        }
    }

    //triggerNotification func goes here
}

triggerNotification function:

func triggerNotification(){
    let content = UNMutableNotificationContent()
    content.title = NSString.localizedUserNotificationString(forKey: "Notification Testing", arguments: nil)
    content.body = NSString.localizedUserNotificationString(forKey: "This is a test", arguments: nil)
    content.sound = UNNotificationSound.default()
    content.badge = (UIApplication.shared.applicationIconBadgeNumber + 1) as NSNumber;
    let trigger = UNTimeIntervalNotificationTrigger(
        timeInterval: 1.0,
        repeats: false)

    let request = UNNotificationRequest.init(identifier: "testTriggerNotif", content: content, trigger: trigger)

    let center = UNUserNotificationCenter.current()
    center.add(request)
}

What am I doing wrong?

like image 401
Dinuka Jay Avatar asked Jan 04 '23 20:01

Dinuka Jay


1 Answers

You were missing the handling, when the app is in foreground, you were not specifying how the notifications would look like or be presented.

Set below line while adding notification to specify that you want to show banner while user is using app (iOS 10 new feature).

Add the following line of code when constructing your UNMutableNotificationContent object:

content.setValue("YES", forKeyPath: "shouldAlwaysAlertWhileAppIsForeground")

You should also add the following method in your AppDelegate:

// This method will be called when app received push notifications in foreground

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler(UNNotificationPresentationOptions.alert)        
}
like image 84
Muhammad Adnan Avatar answered Jan 16 '23 03:01

Muhammad Adnan