iOS how to set Alarm and schedule work/notifications

落花浮王杯 提交于 2019-12-01 11:19:09

You many have to schedule local notification which is now available in UNUserNotificationCenter.

So,

  1. For Scheduling a Notification Locally from Your App, follow this doc.
  2. For Handling Notifications and Notification-Related Actions, follow this doc.

To Handle Notifications in your AppDelegate or where you want to handle UNUserNotificationCenter delegate method, add below code:

class AppDelegate:NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate{

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {


    let center = UNUserNotificationCenter.current()
    center.delegate = self // Don't forgot to set delegate

    //To get permissions from user:
    let options: UNAuthorizationOptions = [.alert, .sound, .badge];
    center.requestAuthorization(options: options) {
        (granted, error) in
        if !granted {
            print("Something went wrong")
        }
    }

    return true
}
}
  1. You can use local notifications for getting an alarm notifications.
  2. You can handle the click in the delegate method of UNUserNotificationCenterDelegate and navigate to the desired page.

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) 
    
  3. For displaying notification when app is in foreground use this method from same delegate

        func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
    
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!