使用 UNUserNotificationCenter iOS 10

Using UNUserNotificationCenter for iOS 10

尝试使用 Firebase 注册远程通知,但是在执行以下代码时出现错误:

UNUserNotificationCenter is only available on iOS 10.0 or newer

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        var soundID: SystemSoundID = 0
        let soundFile: String = NSBundle.mainBundle().pathForResource("symphony", ofType: "wav")!
        let soundURL: NSURL = NSURL(fileURLWithPath: soundFile)
        AudioServicesCreateSystemSoundID(soundURL, &soundID)
        AudioServicesPlayAlertSound(soundID)
        Fabric.with([Twitter.self])


        //Firebase configuration
        FIRApp.configure()

        //Resource code from Whosebug to create UNUserNotificationCenter
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
            // Enable or disable features based on authorization.
        }
        application.registerForRemoteNotifications()
        return true
    }

通过创建一个基于 OS 版本号的 if 语句,通过简单的 "Fix-it" 并不能解决我的问题。对于 UserNotifications 框架的这个解决方案,我应该做什么或考虑什么?

一方面,对于新的 UNUserNotificationCenter,您只想在用户授予权限的情况下注册远程通知。您的代码设置方式,无论许可如何,您都试图这样做,这可能是原因之一。你应该这样做:

import UserNotifications

...

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in

        DispatchQueue.main.async {
            UIApplication.shared.registerForRemoteNotifications()
        }

    }

    return true
}

如果您需要检查用户的 OS 是否低于 iOS 10.0 - 您可以尝试像这样包含旧系统:

if #available(iOS 10.0, *) {

    UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in

        DispatchQueue.main.async {
            UIApplication.shared.registerForRemoteNotifications()
        }

    }

} else {

    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert |
        UIUserNotificationType.Badge, categories: nil))
}

让我知道这是否有效,以及这是否是您想要完成的。如果没有,我会删除我的答案。