2017-07-21 50 views
3

我想在應用程序處於前臺時顯示推送通知的標題。而我實現這個方法來顯示通知:使用未聲明的類型'UNUserNotificationCenter'

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) 
     { 
      completionHandler([.alert, .badge, .sound]) 
     } 

但收到此錯誤未申報類型的使用「UNUserNotificationCenter」 enter image description here

+3

您是否添加了'import UserNotifications'? –

+0

不讓我導入它 –

+0

我導入錯誤已解決,但尚未收到通知 –

回答

5

所有你需要做的是導入UserNotifications框架:

import UserNotifications 

此外,請確保您符合UNUserNotificationCenterDelegate。 作爲一個很好的做法,我會建議通過實現它作爲一個extension做到這一點:

如果你不熟悉代表團,你可能要檢查this出來。

import UIKit 
// add this: 
import UserNotifications 

class ViewController: UIViewController { 
    . 
    . 
    . 

    // somewhere in your code: 
    UNUserNotificationCenter.current().delegate = delegateObject 
} 

// add this: 
// MARK:- UserNotifications 
extension ViewController: UNUserNotificationCenterDelegate { 
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) 
    { 
     completionHandler([.alert, .badge, .sound]) 
    } 
} 
+0

謝謝這工作正常。 –

相關問題