类型 UNUserNotificationCenter 目前没有成员,swift 2.3

Type UNUserNotificationCenter has no member current, swift 2.3

在 iOS10 中,Apple 重新设计了用户通知。 现在我正在尝试调整我的应用程序以适应这些变化,遵循 this:

let center = UNUserNotificationCenter.current()

给我一个错误:

Type UNUserNotificationCenter has no member current, swift 2.3

我知道该教程可能适用于 swift3。但我需要让它在 swift 2.3 中工作。是否可行,如果可行,如何实现?

文档似乎自相矛盾。虽然它描述了 current() 方法并说要使用它,但示例显示 let center = UNUserNotificationCenter.currentNotificationCenter().

正如您所说,这可能是 Swift 版本依赖性。

对于 Xcode 8 / ios9/10

只需使用:

import  UserNotifications

。 .

    // swift 3.0:
    if #available(iOS 10.0, *) {
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
            // Enable or disable features based on authorization.
        }

    } else {
        // Fallback on earlier versions
    }

// 注意:如果在前台,您将永远不会被调用! :)

导入这个:

import  UserNotifications

在您的 appDelegate 文件中实现此委托:

UNUserNotificationCenterDelegate

这将使您可以访问以下方法:

func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) {}

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {}

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {}

然后将其添加到您的应用委托的 didFinishLaunchWithOptions 方法中以将其全部绑定。

if #available(iOS 10.0, *) {
    // For iOS 10 display notification (sent via APNS)
    UNUserNotificationCenter.current().delegate = self

    let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
    UNUserNotificationCenter.current().requestAuthorization(
        options: authOptions,
        completionHandler: {_, _ in })
} else {
    let settings: UIUserNotificationSettings =
        UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
    application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()

swift 4.1

if #available(iOS 10.0, *) {

UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate

    let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
    UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: {_, _ in
        self.getNotificationSettings()
    })

} else {
    // Fallback on earlier versions
    let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
    UIApplication.shared.registerUserNotificationSettings(settings)
}
DispatchQueue.main.async {
    UIApplication.shared.registerForRemoteNotifications()
}