registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

前端 未结 15 1723
时光说笑
时光说笑 2020-11-29 15:09

When trying to register for push notifications under iOS 8.x:

application.registerForRemoteNotificationTypes(UIRemoteNotificationType.Alert | UIRemoteNotific         


        
15条回答
  •  长情又很酷
    2020-11-29 15:33

    iOS 8 has changed notification registration in a non-backwards compatible way. While you need to support iOS 7 and 8 (and while apps built with the 8 SDK aren't accepted), you can check for the selectors you need and conditionally call them correctly for the running version.

    Here's a category on UIApplication that will hide this logic behind a clean interface for you that will work in both Xcode 5 and Xcode 6.

    Header:

    //Call these from your application code for both iOS 7 and 8
    //put this in the public header
    @interface UIApplication (RemoteNotifications)
    
    - (BOOL)pushNotificationsEnabled;
    - (void)registerForPushNotifications;
    
    @end
    

    Implementation:

    //these declarations are to quiet the compiler when using 7.x SDK
    //put this interface in the implementation file of this category, so they are
    //not visible to any other code.
    @interface NSObject (IOS8)
    
    - (BOOL)isRegisteredForRemoteNotifications;
    - (void)registerForRemoteNotifications;
    
    + (id)settingsForTypes:(NSUInteger)types categories:(NSSet*)categories;
    - (void)registerUserNotificationSettings:(id)settings;
    
    @end
    
    @implementation UIApplication (RemoteNotifications)
    
    - (BOOL)pushNotificationsEnabled
    {
        if ([self respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
        {
            return [self isRegisteredForRemoteNotifications];
        }
        else
        {
            return ([self enabledRemoteNotificationTypes] & UIRemoteNotificationTypeAlert);
        }
    }
    
    - (void)registerForPushNotifications
    {
        if ([self respondsToSelector:@selector(registerForRemoteNotifications)])
        {
            [self registerForRemoteNotifications];
    
            Class uiUserNotificationSettings = NSClassFromString(@"UIUserNotificationSettings");
    
            //If you want to add other capabilities than just banner alerts, you'll need to grab their declarations from the iOS 8 SDK and define them in the same way.
            NSUInteger UIUserNotificationTypeAlert   = 1 << 2;
    
            id settings = [uiUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert categories:[NSSet set]];            
            [self registerUserNotificationSettings:settings];
    
        }
        else
        {
            [self registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert];
        }
    }
    
    @end
    

提交回复
热议问题