iOS7 崩溃时注册远程 notificaitons

标签: ios Objective-C
发布时间: 2017/3/31 20:35:01
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

这种方式很好运行在 iOS8,但当我把它放在 iOS7 设备上,它的崩溃给我错误

-[UIApplication registerUserNotificationSettings:]: unrecognized selector sent to instance 0x14e56e20

我注册在通知我 AppDelegate :

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

#ifdef __IPHONE_8_0
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeBadge
                                                                                         |UIRemoteNotificationTypeSound
                                                                                         |UIRemoteNotificationTypeAlert) categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
#else
    //register to receive notifications
    UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
#endif

    application.applicationIconBadgeNumber = 0;

    return YES;
}

当在设置断点时,它总是运行的代码 __IPHONE_8_0 块。我怎么可以检测哪些块运行?

解决方法 1:

你不应该用这样的预处理器。更好的方法是检查是否您的对象来响应消息要发送它而不检查操作系统版本。改变你的方法

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    if ([application respondsToSelector:@selector(registerUserNotificationSettings:)])
    {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeBadge
                                                                                             |UIRemoteNotificationTypeSound
                                                                                             |UIRemoteNotificationTypeAlert) categories:nil];
        [application registerUserNotificationSettings:settings];
    }
    else
    {
        //register to receive notifications
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
        [application registerForRemoteNotificationTypes:myTypes];
    }
    application.applicationIconBadgeNumber = 0;

    return YES;
}

这里要注意的几个事情。我改变了 [UIApplication sharedApplication]application 因为委托已经通过在你 UIApplication 实例,所以只是直接访问。

respondsToSelector:是一种方法从 NSObject 它会告诉你如果一个接收器, application ,将响应一个选择器 (或方法)。你只需要像方法包裹 @selector(myMethod:) 检查它。这是一个好的习惯进入为向后兼容性目的时使用较新的 Api。你还想做这样的检查,当处理匿名类型对象的 id

至于为什么 #ifdef __IPHONE_8_0 没工作,检查了这个答案︰ http://stackoverflow.com/a/25301879/544094

官方微信
官方QQ群
31647020