如何在Swift中安排通知

时间:2018-06-30 20:50:11

标签: ios swift uilocalnotification unusernotificationcenter

我正在尝试在项目中安排通知。我没有收到任何错误或运行时崩溃,但是由于某种原因,在进行调度时我没有在模拟器上收到任何通知。我不确定我到底要去哪里,因为我在上一个项目中已经成功做到了。

有人有什么建议吗?

import UserNotifications

func addNotification(title: String, category: String, UI: String, date: Date) {

    // Remove Notification

    removeNotifcation(UI: UI)

    // Create Notification
    // iOS 10 Notification

    if #available(iOS 10.0, *) {

        let notif = UNMutableNotificationContent()

        notif.title = title
        notif.subtitle = "Reminder for \(title)"
        notif.body = "Your Reminder for \(title) set for \(date)"
        notif.sound = UNNotificationSound.default()
        notif.categoryIdentifier = UI

        let today = Date()

        let interval = date.timeIntervalSince(today as Date)

        let notifTrigger = UNTimeIntervalNotificationTrigger(timeInterval: interval, repeats: false)

        let request = UNNotificationRequest(identifier: title, content: notif, trigger: notifTrigger)

        UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
            if error != nil {
                print(error as Any)
                // completion(Success: false)
            } else {
                //completion(Sucess: true)
            }
        })
    } else {
        let newNotification:UILocalNotification = UILocalNotification()

        newNotification.category = category
        newNotification.userInfo = [ "UUID"  : UI]
        newNotification.alertBody = "Your reminder for \(title)"
        newNotification.fireDate = date
        //notification.repeatInterval = nil
        newNotification.soundName = UILocalNotificationDefaultSoundName

        UIApplication.shared.scheduleLocalNotification(newNotification)

    }

}

func removeNotifcation(UI: String) {

    //Remove Notif
    //iOS 10 Notification
    if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [UI])
    } else {
        //Remove Notif

        let app:UIApplication = UIApplication.shared
        for oneEvent in app.scheduledLocalNotifications! {
            let notification = oneEvent as UILocalNotification
            let userInfoCurrent = notification.userInfo!
            let uuid = userInfoCurrent["UUID"] as! String
            if uuid == UI {
                //Cancelling local notification
                app.cancelLocalNotification(notification)
                break;
            }
        }
    }

}

这就是我调用方法的方式

dataManager.addNotification(title: "String", category: "001", UI: uuid, date: datePicker.date)

1 个答案:

答案 0 :(得分:1)

只有当您实现willPresent委托方法并且由于以下原因时,通知仅在应用程序位于前台时才会出现

 let today = Date()

此日期会在您运行它时触发,因此添加一个时间间隔并将应用发送到后台,您将看到它,并确保您在AppDelegate中请求它的许可

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

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
        print("granted: (\(granted)")
    }

  return true
}

您还可以看看此tutorial

//

编辑:以验证它是否触发了实现

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

      print("handling notifications with the TestIdentifier Identifier")

     completionHandler()

}

并将委托设置为VC

UNUserNotificationCenter.current().delegate = self