使用适用于iOS 10的UNUserNotificationCenter

Cos*_*ows 4 apple-push-notifications swift firebase-cloud-messaging

尝试使用Firebase注册远程通知,但是在实现以下代码时,我收到错误:

UNUserNotificationCenter仅适用于iOS 10.0或更高版本

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 stackoverflow 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
    }
Run Code Online (Sandbox Code Playgroud)

通过简单的"修复它"不能通过基于操作系统版本号创建if语句来解决我的问题.对于UserNotifications框架,我应该做什么或想到这个解决方案?

Pie*_*rce 8

首先,使用new UNUserNotificationCenter,您只想在用户授予权限时注册远程通知.您的代码设置方式,无论是否允许,您都尝试这样做,这可能是其中一个原因.你应该做这样的事情:

import UserNotifications

...

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

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

        if granted {
            UIApplication.shared.registerForRemoteNotifications()
        }

    }

    return true
}
Run Code Online (Sandbox Code Playgroud)

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

if #available(iOS 10.0, *) {

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

        if granted {
            UIApplication.shared.registerForRemoteNotifications()
        }

    }

} else {

    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert |
        UIUserNotificationType.Badge, categories: nil))
}
Run Code Online (Sandbox Code Playgroud)

让我知道这是否有效,如果这是你想要完成的.如果没有,我会删除我的答案.

  • 如果您提到需要为我这样的傻瓜导入UserNotifications,可能会有所帮助. (4认同)