在 Xcode 8/Swift 3.0 中注册推送通知? [英] Registering for Push Notifications in Xcode 8/Swift 3.0?

查看:35
本文介绍了在 Xcode 8/Swift 3.0 中注册推送通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让我的应用在 Xcode 8.0 中运行,但遇到了错误.我知道这段代码在以前版本的 swift 中运行良好,但我假设在新版本中更改了此代码.这是我尝试运行的代码:

I'm trying to get my app working in Xcode 8.0, and am running into an error. I know this code worked fine in previous versions of swift, but I'm assuming the code for this is changed in the new version. Here's the code I'm trying to run:

let settings = UIUserNotificationSettings(forTypes: [.Sound, .Alert, .Badge], categories: nil)     
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.shared().registerForRemoteNotifications()

我得到的错误是参数标签 '(forTypes:, Categories:)' 与任何可用的重载不匹配"

The error that I'm getting is "Argument labels '(forTypes:, categories:)' do not match any available overloads"

是否有其他命令可以让我尝试使其正常工作?

Is there a different command that I could try to get this working?

推荐答案

导入UserNotifications框架并在AppDelegate.swift中添加UNUserNotificationCenterDelegate

Import the UserNotifications framework and add the UNUserNotificationCenterDelegate in AppDelegate.swift

请求用户权限

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


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

获取设备令牌

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

    let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    print(deviceTokenString)
}

如有错误

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {

        print("i am not available in simulator (error)")
}

如果您需要知道授予的权限

UNUserNotificationCenter.current().getNotificationSettings(){ (settings) in

            switch settings.soundSetting{
            case .enabled:

                print("enabled sound setting")

            case .disabled:

                print("setting has been disabled")

            case .notSupported:
                print("something vital went wrong here")
            }
        }

这篇关于在 Xcode 8/Swift 3.0 中注册推送通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆