2017-02-18 23 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

不客气!我同意;通常通知的工作方式有点不尽如人意 - 非常多的远程通知。 –