在特定时间发出本地通知

时间:2017-08-03 12:42:33

标签: swift3 nsusernotificationcenter

请问有关如何在特定时间触发本地通知的问题?没有用户触发它并且需要在特定时间点击应用本地通知

以下我的代码:

这是为了获得用户的许可

func registerLocal() {

    let center = UNUserNotificationCenter.current()

    center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
        if granted {
            print("Yay!")
        } else {
            print("D'oh")
        }
    }
}

//这我安排了本地通知     func scheduleLocal(){

    let center = UNUserNotificationCenter.current()
    let content = UNMutableNotificationContent()
    content.title = "Late wake up call"
    content.body = "The early bird catches the worm, but the second mouse gets the cheese."
    content.categoryIdentifier = "alarm"
    content.userInfo = ["customData": "fizzbuzz"]
    content.sound = UNNotificationSound.default()



    var dateComponents = DateComponents()
    dateComponents.hour = 3
    dateComponents.minute = 19
    dateComponents.day = 3
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
    center.add(request)
     center.removeAllPendingNotificationRequests()
}

//她称之为论文方法

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

            registerLocal()
            scheduleLocal()
         return true
  }

当我关闭我的应用程序时,我没有收到通知,请帮助我如何在特定时间触发本地通知

谢谢

1 个答案:

答案 0 :(得分:1)

添加通知后,您不应致电center.removeAllPendingNotificationRequests(),因为它也会取消之前添加的待处理通知。您应该在致电center.addRequest(request)后确认是否已实际添加了您的请求

center.getPendingNotificationRequests(completionHandler: { pendingRequest in
    print("Pending notifications: \(pendingRequest)")   //Just for debugging
})

或者您也可以为addRequest指定一个完成处理程序,如果请求未成功添加,则会返回错误:

center.add(request, withCompletionHandler: { error in
   print(error)
})