注册iOS推送通知时出现奇怪的行为

时间:2015-03-02 18:40:26

标签: ios swift ios8 xcode6 apple-push-notifications

这是我在AppDelegate中输入的用于注册推送通知的代码:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {  
    let notificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
    let settings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)
    UIApplication.sharedApplication().registerUserNotificationSettings(settings)
    return true
}

func application(application:UIApplication!, didRegisterForUserNotificationSettings notificationSettings:UIUserNotificationSettings) {
    println("[AppDelegate][didRegisterForUserNotificationSettings]")
    UIApplication.sharedApplication().registerForRemoteNotifications()
}

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
    println("[AppDelegate][didFailToRegisterForRemoteNotificationsWithError]")
    println(error)
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    println("[AppDelegate][didRegisterForRemoteNotificationsWithDeviceToken]")
    println(deviceToken)
}

当我通过Xcode 6.1.1在我的iPhone上启动应用程序时,没有任何反应,我看不到我的println输出,但是当我离开应用程序并转到设置 - >通知我发现我的应用程序启用了推送通知。

由于未调用didRegisterForRemoteNotificationsWithDeviceToken,我无法获得deviceToken

我做错了什么?

2 个答案:

答案 0 :(得分:0)

也许问题是,在app完成启动时调用的app delegate方法返回registerForRemoteNotifications()后,您正在调用true。试试这个:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {  
    let notificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
    let settings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)

    application.registerUserNotificationSettings(settings)
    application.registerForRemoteNotifications() 

    return true
}

答案 1 :(得分:0)

我去了手机的设置 - >去一般 - >通知 - >选择你的应用 - >通知中心 - >把它改成10!更改后我开始获取设备令牌数据!