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?
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With