2017-02-04 51 views

回答

1

在您的應用程序委託中,將對象配置爲用戶通知中心的UNUserNotificationCenterDelegate並執行userNotificationCenter(_:didReceive:withCompletionHandler:)

需要注意的是,如果用戶僅僅駁回通知提醒,這種方法會不會稱爲除非您還配置對應於該通知的類別(UNNotificationCategory),與.customDismissAction選項。

1

UILocalNotification在iOS 10中已棄用。您應該改爲使用UserNotifications框架。

所有此之前不要忘import UserNotifications

首先,你應該建立UNUserNotificationCenterDelegate

extension AppDelegate: UNUserNotificationCenterDelegate { 
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping() -> Void) { 
     // - Handle notification 
    } 
} 

比設置UNUserNotificationCenter的代表。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
     UNUserNotificationCenter.current().delegate = self 
     UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { (accepted, _) in 
      if !accepted { 
       print("Notification access denied.") 
      } 
     } 
     return true 
    } 

現在您可以設置您的通知。

func setup(at: Date) { 
     let calendar = Calendar.current 
     let components = calendar.dateComponents(in: .current, from: date) 
     let newComponents = DateComponents(calendar: calendar, timeZone: .current, 
     month: components.month, day: components.day, hour: components.hour, minute: components.minute) 

     let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false) 

     let content = UNMutableNotificationContent() 
     content.title = "Reminder" 
     content.body = "Just a reminder" 
     content.sound = UNNotificationSound.default() 

     let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger) 

     UNUserNotificationCenter.current().removeAllPendingNotificationRequests() 
     UNUserNotificationCenter.current().add(request) {(error) in 
      if let error = error { 
       print("Uh oh! We had an error: \(error)") 
      } 
     } 
    } 

最後處理它!

extension AppDelegate: UNUserNotificationCenterDelegate { 
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping() -> Void) { 
     if response.notification.request.identifier == "textNotification" { 
      let appDelegate = UIApplication.shared.delegate as! AppDelegate 
      guard let rootVc = appDelegate.window?.rootViewController else { return } 
      let alert = UIAlertController(title: "Notification", message: "It's my notification", preferredStyle: .alert) 
      let action = UIAlertAction(title: "OK", style: .cancel, handler: nil) 
      alert.addAction(action) 
      rootVc.present(alert, animated: true, completion: nil) 
     } 
    } 
} 
相關問題