Wednesday, November 25, 2015

How to check API availability in Swift?

If you are working with Swift then you need to be very careful to use the iOS specific API. As before Swift 2.0, there were no standard way to check the availability of any API or method.

Swift 2.0 introduced the “#available“ to check the API availability or run version specific code in blocks . If you are developing the application with deployment target 8.0 with base sdk 9.0. You need to use the API which is available in iOS 9 only then you could do this by checking the API availability. 

If you will not check the API availability then it will give you a compiler error. To prevent this error, you need to check the API availability.

if #available(iOS 9, *) {
            let stackView = UIStackView()
            // do iOS 9 stuff
        }

Using the availability syntax we will check whether we are running iOS 9 or later and if so will execute the code.

You can also add the availability check for the instance method and classes by inserting the given line above the method definition or at the top of the class.

@available(iOS 8.0, *)
    func iOS8Method() {
        // do stuff
        
    }

You can’t use this method without availability check if your deployment target is below 8.0. This method will run above iOS8.0 target. 

The * at the end is used to refer all the Future platforms that Apple introduces, and it's required.