iOS: how to register for push notifications?

2019-04-20 18:41发布

问题:

I'm trying to implement Push Notifications for my iOS 5 application by the guide from Ray Wenderlich: http://www.raywenderlich.com/3443/apple-push-notification-services-tutorial-part-12.

I've inserted the following into my didFinishLaunchingWithOptions method in my AppDelegate:

[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
    (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];

When running the application on my device (not simulator) the popup/alert telling me to accept push notifications isn't displayed. I've inserted a debug-point on the line, and I can see, that the registerForRemoteNotificationTypes is called.

Why is nothing happening?

回答1:

Maybe, delete your app and try again. That dialog only appears once. But I'm not sure that whether that dialog will appear again when you reinstall that app.

You can also go to your setting app the notification center, see if your app is on the list.

You can also add a break point and see if didRegisterForRemoteNotificationsWithDeviceToken executes.



回答2:

I had this exact issue (with the same tutorial no less), and found that I was signing the code with the wrong provisioning profile.

Specifically, I only enabled "Production" push notifications for my app (since I didn't want to make certificates twice etc) but my Build Settings in Xcode used "iPhone Development" as the default "Code Signing Identity" for "Release", rather than "iPhone Distribution" as it should have been. This seemed to be the default setting in my test app.

Hopefully I can stop someone else wasting time on the same problem.



回答3:

From iOS 8 there's new method for this. Straight from UIApplication.h:

- (void)registerForRemoteNotifications NS_AVAILABLE_IOS(8_0);

Calling this will result in either application:didRegisterForRemoteNotificationsWithDeviceToken: or application:didFailToRegisterForRemoteNotificationsWithError: to be called on the application delegate.

Note: these callbacks will be made only if the application has successfully registered for user notifications with registerUserNotificationSettings:, or if it is enabled for Background App Refresh.