#ifdef __IPHONE_8_0代码也在iOS 7上运行

时间:2014-08-14 06:50:36

标签: ios7 apple-push-notifications ios8

我的应用程序中有以下代码 - 我在iOS 7上看到了与评论一致的一些崩溃。

+ (void)registerDeviceForRemoteNotifications {
#if !TARGET_IPHONE_SIMULATOR
    if ([[KOAAuthenticator sharedAuthenticator] currentUser] != nil) {
        UIApplication *sharedApplication = [UIApplication sharedApplication];
#ifdef __IPHONE_8_0
        [sharedApplication registerForRemoteNotifications]; // <--- CRASH HERE
#else
        [sharedApplication registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
#endif
    }
#endif
}

Crashlytics说:-[UIApplication registerForRemoteNotifications]: unrecognized selector sent to instance 0x157d04290

怎么可能呢?不应该在iOS 7上调用此代码,对吧?

编辑:解决方案

+ (void)registerDeviceForRemoteNotifications {
#if !TARGET_IPHONE_SIMULATOR
    if ([[KOAAuthenticator sharedAuthenticator] currentUser] != nil) {

        UIApplication *sharedApplication = [UIApplication sharedApplication];

#ifdef __IPHONE_8_0
        if ([sharedApplication respondsToSelector:@selector(registerForRemoteNotifications)]) {
            [sharedApplication registerForRemoteNotifications];
        } else {
            [sharedApplication registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
        }
#else
        [sharedApplication registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
#endif

    }
#endif
}

2 个答案:

答案 0 :(得分:15)

您的代码仅添加了对旧版Xcode和iOS SDK的编译支持。

您应该在运行时添加以下检查:

#ifdef __IPHONE_8_0
        if(NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1) {
            [sharedApplication registerForRemoteNotifications]; // <--- CRASH HERE
        }
        else
#endif
        {
            [sharedApplication registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
        }

答案 1 :(得分:5)

ifdef是在编译(或更确切地说是预处理)时计算的,而不是在运行时,因此构建的二进制文件中包含哪两个registerForRemoteNotifications调用只取决于您使用哪个SDK构建,而不是运行在哪个设备上