【发布时间】:2017-07-05 12:54:32
【问题描述】:
我已经在我的 AppDelegate 中完成了这项工作
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {(didAllow, error) in
if didAllow{
print("Notification access granted")
}
else{
print(error?.localizedDescription as Any)
}
})
在我的 ViewController 类中,我已经完成了这个方法来调用按钮操作
func sendNotification(inSecond: TimeInterval, completion: @escaping (_ Success: Bool) -> ()){
let notify = UNMutableNotificationContent()
notify.title = "Break Oil"
notify.subtitle = "Please renew your Break Oil"
notify.sound = UNNotificationSound(named: "carsHrn.mp3")
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: inSecond, repeats: false)
let request = UNNotificationRequest(identifier: "myNotification", content: notify, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
if error != nil{
print(error!)
completion(false)
}
else {
completion(true)
}
})
}
【问题讨论】:
-
你实现
UNUserNotificationCenterDelegate的委托方法:func userNotificationCenter(_:willPresent:withCompletionHandler:)了吗?否则,当您的应用在前台时,您将不会收到通知。 -
我应该在哪里实现这个,在 appDelegate 或视图控制器类中?
-
我猜你在理解 iOS 中代理的工作方式方面存在一些差距。您应该详细研究委托模式(例如如何采用/遵守协议,如何处理委托方法等)。问“我应该在哪里写这个”不是一个好问题。顺便说一句,暂时看看这个Local Notifications With the User Notifications Framework 教程以满足您的需要。
-
我已经实现了 ... func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { print("Tapped in notification") } func userNotificationCenter (_ center: UNUserNotificationCenter, willPresent 通知: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) { print("Notification正在被触发") completionHandler( [.alert,.sound,.badge]) } }
-
仍然无法正常工作,这就是我问你的原因..
标签: swift3