Unable to register for Push Notifications (Xcode 7

2019-02-19 05:25发布

问题:

I've upgraded my devices to iOS 9 and my Xcode environment to 7.0 (7A220). My app registers for notifications via:

[[UIApplication sharedApplication] registerForRemoteNotifications];

However, neither "didRegisterForRemoteNotificationWithDeviceToken" or "didFailToRegisterForRemoteNotificationsWithError" are called. Furthermore, my app does not appear in the Settings->Notifications section (which tells me its not even trying to register for remote/push notifications)

My App ID has the following Application Services enabled:

  • Game Center
  • In-App Purchase
  • Push Notifications

In Xcode, the following capabilities enabled:

  • Push Notifications

  • Background Modes (Remote Notifications)

This worked fine with iOS 8, with app built with Xcode 6. Also, it no longer works with an iOS 8 device when built with Xcode 7.

回答1:

Do you use a simulator?

In a simulator, remote notifications are not supported.

sample code:

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

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
    application.registerForRemoteNotifications()
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    let token=deviceToken.description
    print(token)
}

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
    print(error)
}

Xcode says:

Error Domain=NSCocoaErrorDomain
Code=3010 "REMOTE_NOTIFICATION_SIMULATOR_NOT_SUPPORTED_NSERROR_DESCRIPTION"
UserInfo={NSLocalizedDescription=REMOTE_NOTIFICATION_SIMULATOR_NOT_SUPPORTED_NSERROR_DESCRIPTION}


回答2:

The reason why it wasn't working was because I wasn't calling:

[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];

Prior to the call:

[[UIApplication sharedApplication] registerForRemoteNotifications];