Reputation: 2929
I'm new to notifications in swift and have setup the following in my AppDelegate.swift file. It runs and I get print output that the notifications are setup and do not error. I also get the permission ask for notifications, which I click yes to. I believe the interval notification I have should trigger in 20 seconds after launch. It does not trigger, this doesn't change if I'm in the app or have minimized the app. Note I am running in Simulator mode from XCODE. Why is my notification not triggering?
func setupNotifications(){
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
print("Yay!")
} else {
print("D'oh")
}
}
notificationCenter.removeAllPendingNotificationRequests()
print("setting up notifications")
let content = UNMutableNotificationContent()
content.title = "Answer your daily questions"
content.body = "Answer your daily questions please"
content.categoryIdentifier = "alarm"
content.userInfo = ["customData": "fizzbuzz"]
content.sound = UNNotificationSound.default
//let trigger = UNTimeIntervalNotificationTrigger(timeInterval: (1*60), repeats: true)
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 20, repeats: false)
// Create the request
let request = UNNotificationRequest(identifier: "daily-notifier",
content: content, trigger: trigger)
// Schedule the request with the system.
notificationCenter.add(request) { (error) in
if error != nil {
print("there were errors to address")
// Handle any errors.
}
}
print("done setting up notifications")
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let path = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true)
print("\(path)")
// Override point for customization after application launch.
setupNotifications()
return true
}
Upvotes: 1
Views: 1671
Reputation: 517
First note that you should probably wait to receive permission before adding a request for a local notification as per Apple's documentation of the requestAuthorization(options:completionHandler:)
Note: Always call this method before scheduling any local notifications and before registering with the Apple Push Notification service.
Also make sure that you've added Push Notifications as a capability for your app as this will be needed should you submit it.
After I ran the above code I did not receive a notification while the app was still active but I did receive one while the app was in the background. I believe that if a user receives a notification for an app that is in the active state it is given silently; i.e., without the banner and sound (at least this is what I have experienced with my notifications, although there may be more to it).
Upvotes: 3