使用 NSUserActivity 和 CoreSpotlight 但仍将 iOS8 设置为部署目标

Use NSUserActivity and CoreSpotlight but still set iOS8 as Deployment Target

是否可以使用 iOS9 的新功能,例如 NSUserActivityCoreSpotlight,但仍将我的开发目标设置为 8.2,以便 iOS8 的用户仍然可以使用该应用程序吗?

我想我只需要做一个 iOS 版本号检查或使用 respondsToSelector:.

这是正确的吗?

是的,我在我的一个应用程序中执行此操作(实际上部署目标是 iOS 7)。做起来很简单。只需确保 CSSearchableIndex class 存在,使 CoreSpotlight 框架可选,并正确编写代码以防止较新的 API 在具有较早版本 iOS.

您甚至可以保护代码,以便它在 Xcode 6 下编译,如果您有某种理由这样做的话。

示例:

// Ensure it only compiles with the Base SDK of iOS 9 or later
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 90000
    // Make sure the class is available and the device supports CoreSpotlight
    if ([CSSearchableIndex class] && [CSSearchableIndex isIndexingAvailable]) {
        dispatch_async(_someBGQueue, ^{
            NSString *someName = @"Some Name";
            CSSearchableIndex *index = [[CSSearchableIndex alloc] initWithName:someName];
            // rest of needed code to index with Core Spotlight
        });
    }
#endif

在您的应用委托中:

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 90000
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void(^)(NSArray *restorableObjects))restorationHandler {
    if ([[userActivity activityType] isEqualToString:CSSearchableItemActionType]) {
        // This activity represents an item indexed using Core Spotlight, so restore the context related to the unique identifier.
        // The unique identifier of the Core Spotlight item is set in the activity’s userInfo for the key CSSearchableItemActivityIdentifier.
        NSString *uniqueIdentifier = [userActivity.userInfo objectForKey:CSSearchableItemActivityIdentifier];
        if (uniqueIdentifier) {
            // process the identifier as needed
        }
    }

    return NO;
}
#endif