在Xcode 8/Swift 3.0中注册推送通知?

Ash*_*rne 116 push-notification ios swift3 ios10 unusernotificationcenter

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

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

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

是否有一个不同的命令,我可以尝试使其工作?

LC *_*C 웃 298

导入UserNotifications框架并添加UNUserNotificationCenterDelegateAppDelegate.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
}
Run Code Online (Sandbox Code Playgroud)

获取设备令牌

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

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

如果有错误

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

        print("i am not available in simulator \(error)")
}
Run Code Online (Sandbox Code Playgroud)

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

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

  • @PavlosNicolaou导入UserNotifications框架 (4认同)

Bra*_*don 46

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

    if #available(iOS 10, *) {

        //Notifications get posted to the function (delegate):  func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void)"


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

            guard error == nil else {
                //Display Error.. Handle Error.. etc..
                return
            }

            if granted {
                //Do stuff here..

                //Register for RemoteNotifications. Your Remote Notifications can display alerts now :)
                DispatchQueue.main.async {
                    application.registerForRemoteNotifications()
                }
            }
            else {
                //Handle user denying permissions..
            }
        }

        //Register for remote notifications.. If permission above is NOT granted, all notifications are delivered silently to AppDelegate.
        application.registerForRemoteNotifications()
    }
    else {
        let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
        application.registerForRemoteNotifications()
    }

    return true
}
Run Code Online (Sandbox Code Playgroud)

  • 在闭包中,您需要在主线程上执行与UI相关的任务... DispatchQueue.main.async {...在这里执行操作...} (3认同)

Jal*_*zir 25

import UserNotifications  
Run Code Online (Sandbox Code Playgroud)

接下来,转到目标的项目编辑器,然后在"常规"选项卡中,查找"链接的框架和库"部分.

单击+并选择UserNotifications.framework:

// iOS 12 support
if #available(iOS 12, *) {  
    UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound, .provisional, .providesAppNotificationSettings, .criticalAlert]){ (granted, error) in }
    application.registerForRemoteNotifications()
}

// iOS 10 support
if #available(iOS 10, *) {  
    UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
    application.registerForRemoteNotifications()
}
// iOS 9 support
else if #available(iOS 9, *) {  
    UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
    UIApplication.shared.registerForRemoteNotifications()
}
// iOS 8 support
else if #available(iOS 8, *) {  
    UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
    UIApplication.shared.registerForRemoteNotifications()
}
// iOS 7 support
else {  
    application.registerForRemoteNotifications(matching: [.badge, .sound, .alert])
}
Run Code Online (Sandbox Code Playgroud)

使用通知委托方法

// Called when APNs has assigned the device a unique token
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {  
    // Convert token to string
    let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    print("APNs device token: \(deviceTokenString)")
}

// Called when APNs failed to register the device for push notifications
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {  
    // Print the error to console (you should alert the user that registration failed)
    print("APNs registration failed: \(error)")
}
Run Code Online (Sandbox Code Playgroud)

用于接收推送通知

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    completionHandler(UIBackgroundFetchResult.noData)
}
Run Code Online (Sandbox Code Playgroud)

设置推送通知是为您的应用启用Xcode 8中的功能.只需转到目标的项目编辑器,然后单击Capabilities选项卡.查找推送通知并将其值切换为ON.

请查看以下链接以获取更多通知委托方法

处理本地和远程通知UIApplicationDelegate - 处理本地和远程通知

https://developer.apple.com/reference/uikit/uiapplicationdelegate


tom*_*son 20

我在解决这里的问题时将deviceToken Data对象转换为字符串以发送到我的服务器,其中包含当前的Xcode 8测试版.特别是使用deviceToken.description的那个,如8.0b6中那样将返回"32 Bytes"不是很有用:)

这对我有用...

在Data上创建扩展以实现"hexString"方法:

extension Data {
    func hexString() -> String {
        return self.reduce("") { string, byte in
            string + String(format: "%02X", byte)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在收到注册远程通知的回调时使用它:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let deviceTokenString = deviceToken.hexString()
    // Send to your server here...
}
Run Code Online (Sandbox Code Playgroud)

  • 我也遇到了"32bytes"的问题.很好的解决方案,您可以在线创建转换而无需创建扩展.像这样:`让deviceTokenString = deviceToken.reduce("",{$ 0 + String(格式:"%02X",$ 1)})` (8认同)

tsn*_*kff 17

在iOS10而不是您的代码中,您应该通过以下方式请求通知授权:(不要忘记添加UserNotifications框架)

if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().requestAuthorization([.alert, .sound, .badge]) { (granted: Bool, error: NSError?) in
            // Do something here
        }
    }
Run Code Online (Sandbox Code Playgroud)

此外,正确的代码是(else例如,在之前的条件中使用):

let setting = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
UIApplication.shared().registerUserNotificationSettings(setting)
UIApplication.shared().registerForRemoteNotifications()
Run Code Online (Sandbox Code Playgroud)

最后,确保Push Notificationtarget- > Capabilities- > 下激活Push notification.(设置好On)

  • 等等,我想我明白了!只需导入通知框架.XD (4认同)
  • 非常感谢你的回复!但是,使用该代码,它是说"使用未解析的标识符'UNUserNotificationCenter'" (2认同)

小智 8

这对我有用.首先在AppDelegate中

import UserNotifications
Run Code Online (Sandbox Code Playgroud)

然后:

   func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        registerForRemoteNotification()
        return true
    }

    func registerForRemoteNotification() {
        if #available(iOS 10.0, *) {
            let center  = UNUserNotificationCenter.current()
            center.delegate = self
            center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
                if error == nil{
                    UIApplication.shared.registerForRemoteNotifications()
                }
            }
        }
        else {
            UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
            UIApplication.shared.registerForRemoteNotifications()
        }
    }
Run Code Online (Sandbox Code Playgroud)

得到devicetoken:

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

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

}
Run Code Online (Sandbox Code Playgroud)


laa*_*som 5

请注意,您应该使用主线程执行此操作。

let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
        if granted {
            DispatchQueue.main.async(execute: {
                UIApplication.shared.registerForRemoteNotifications()
            })
        }
    }
Run Code Online (Sandbox Code Playgroud)