首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用UNUserNotificationCenter实现iOS 10

使用UNUserNotificationCenter实现iOS 10
EN

Stack Overflow用户
提问于 2017-01-28 16:59:33
回答 1查看 6.9K关注 0票数 4

然而,尝试使用Firebase注册远程通知时,当实现以下代码时,我会得到错误:

UNUserNotificationCenter仅在iOS 10.0或更高版本上可用

代码语言:javascript
复制
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
    }

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-01-28 17:19:43

首先,使用新的UNUserNotificationCenter,您只希望在用户授予权限的情况下注册远程通知。在您的代码设置方式中,无论权限如何,您都在尝试这样做,这可能是原因之一。你应该这样做:

代码语言:javascript
复制
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
}

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

代码语言:javascript
复制
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))
}

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

票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41912386

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档