23

I want to use NSURLQueryItem in my Swift iOS app. However, that class is only available since iOS 8, but my app should also run on iOS 7. How would I check for class existence in Swift?

In Objective-C you would do something like:

if ([NSURLQueryItem class]) {
    // Use NSURLQueryItem class
} else {
    // NSURLQueryItem is not available
}

Related to this question is: How do you check for method or property existence of an existing class?

There is a nice section in https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/AdvancedAppTricks/AdvancedAppTricks.html#//apple_ref/doc/uid/TP40007072-CH7-SW4 called Supporting Multiple Versions of iOS, which explains different techniques for Objective-C. How can these be translated to Swift?

Florian
  • 5,326
  • 4
  • 26
  • 35
  • Check out this answer, it worked for me: http://stackoverflow.com/a/24956190/84745 – s4y Aug 16 '14 at 19:31

3 Answers3

16

Swift 2.0 provides us with a simple and natural way to do this.It is called API Availability Checking.Because NSURLQueryItem class is only available since iOS8.0,you can do in this style to check it at runtime.

    if #available(iOS 8.0, *) {
        // NSURLQueryItem is available

    } else {
        // Fallback on earlier versions
    }
tounaobun
  • 14,570
  • 9
  • 53
  • 75
15

Simplest way I know of

if NSClassFromString("NSURLQueryItem") != nil {
    println("NSURLQueryItem exists")
}else{
    println("NSURLQueryItem does not exists")
}
Sean
  • 2,106
  • 2
  • 16
  • 24
11

Try this:

if objc_getClass("NSURLQueryItem") != nil {
   // iOS 8 
} else {
   // iOS 7
}

I've also done it like this too:

if let theClass: AnyClass = NSClassFromString("NSURLQueryItem") {
    // iOS 8
} else {
    // iOS 7
}

Or, you can also check system version like so, but this isn't the best practice for iOS dev - really you should check if a feature exists. But I've used this for a few iOS 7 hacks... pragmatism over purity.

    switch UIDevice.currentDevice().systemVersion.compare("8.0.0", options: NSStringCompareOptions.NumericSearch) {
    case .OrderedSame, .OrderedDescending:
        iOS7 = false
    case .OrderedAscending:
        iOS7 = true
    }
bandejapaisa
  • 26,576
  • 13
  • 94
  • 112
  • That "if let theClass" was most useful in my case, where I first need to check if 3rd party class exists and then use it. – JOM Jan 05 '16 at 11:48