我遇到本地通知调度问题(我正在使用所有可用的插槽 - 64)。在慢速设备(iPhone 5C)上耗费大量时间的主要问题长达20秒! 我在这里是怎么做的:
let notificationCenter = UNUserNotificationCenter.current()
for notification in unNotifications { //64 notifications
notificationCenter.add(notification) { _ in
//do nothing here
}
}
我没有找到任何束方法来通过一个方法调用来安排所有通知。可能有什么不对?
答案 0 :(得分:0)
只需按照您将获得缺失的步骤进行操作。
请求通知
// Request Notification Settings
UNUserNotificationCenter.current().getNotificationSettings { (notificationSettings) in
switch notificationSettings.authorizationStatus {
case .notDetermined:
self.requestAuthorization(completionHandler: { (success) in
guard success else { return }
// Schedule Local Notification
})
case .authorized:
// Schedule Local Notification
case .denied:
print("Application Not Allowed to Display Notifications")
}
}
申请授权
// MARK: - Private Methods
private func requestAuthorization(completionHandler: @escaping (_ success: Bool) -> ()) {
// Request Authorization
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (success, error) in
if let error = error {
print("Request Authorization Failed (\(error), \(error.localizedDescription))")
}
completionHandler(success)
}
}
安排通知
private func scheduleLocalNotification() {
// Create Notification Content
let notificationContent = UNMutableNotificationContent()
// Configure Notification Content
notificationContent.title = "Cocoacasts"
notificationContent.subtitle = "Local Notifications"
notificationContent.body = "In this tutorial, you learn how to schedule local notifications with the User Notifications framework."
// Add Trigger
let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 10.0, repeats: false)
// Create Notification Request
let notificationRequest = UNNotificationRequest(identifier: "cocoacasts_local_notification", content: notificationContent, trigger: notificationTrigger)
// Add Request to User Notification Center
UNUserNotificationCenter.current().add(notificationRequest) { (error) in
if let error = error {
print("Unable to Add Notification Request (\(error), \(error.localizedDescription))")
}
}
}
实施代表协议
// Configure User Notification Center
UNUserNotificationCenter.current().delegate = self
extension ViewController: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert])
}
}
测试结果为:
参考: https://cocoacasts.com/local-notifications-with-the-user-notifications-framework