2017-02-18 41 views
1

這是我UNUserNotification斯威夫特UNUserNotification不健全引發

 func scheduleNotification() { 
     UNUserNotificationCenter.current().getNotificationSettings { (notificationSettings) in 
     switch notificationSettings.authorizationStatus { 
     case .notDetermined: 
      self.requestAuthorization(completionHandler: { (success) in 
       guard success else { return } 

       // Schedule Local Notification 
       self.scheduleLocalNotification() 
      }) 

     case .authorized: 
      // Schedule Local Notification 
      self.scheduleLocalNotification() 


     case .denied: 
      print("Application Not Allowed to Display Notifications") 
     } 
     } 
    } 

    private func scheduleLocalNotification() { 
     // Create Notification Content 
     let notificationContent = UNMutableNotificationContent() 

     // Configure Notification Content 
     notificationContent.title = "Hello" 
     notificationContent.body = "" 

     // Add Trigger 
     let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 10.0, repeats: false) 

     // Create Notification Request 
     let notificationRequest = UNNotificationRequest(identifier: id, 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))") 
      } 
     } 
    } 

    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) 
     } 
    } 

它安排了通知呼叫10秒後的代碼和它的作品,通知被呈現在鎖屏上,問題是,它不會觸發任何聲音/振動。
根據要求我設置這些選項[.alert, .sound, .badge],我錯過了什麼?
p.s.我願意設置自定義音效,預設一個足夠

回答

3

你缺少一個將播放聲音的關鍵因素:

notificationContent.sound = UNNotificationSound.default() 

包括UNMutableNotificationContent應該解決您的問題。

+0

是的,這是缺失的行,謝謝。即使它看起來有點奇怪,我必須明確地設置默認值,因爲我在請求中請求了'.sound' :) – r4id4

+0

不客氣!我同意;通常通知的工作方式有點不盡如人意 - 非常多的遠程通知。 –