Checking for API Availability - Swift 2.0, Xcode 7 and Interface Builder - iOS 9 Swift Programming Cookbook (2015)

iOS 9 Swift Programming Cookbook (2015)

Chapter 1. Swift 2.0, Xcode 7 and Interface Builder

1.4 Checking for API Availability

Problem

You want to check whether a specific API is available on the host device running your code.

Solution

Use the #available syntax.

Discussion

We’ve all been waiting for this for a very long time. The days of having to call the respondsToSelector: method are over (hopefully). Now we can just use the #available syntax to make sure a specific iOS version is available before making a call to a method.

Let’s say that we want to write a method that can read an array of bytes from an NSData. NSData offers a handy getBytes: method to do this, but Apple decided to deprecate it in iOS 8.1 and replace it with the better getBytes:length: version that minimizes the risk of buffer overflows. So assuming that one of our deployment targets is iOS 8 or older, we want to ensure that we call this new method if we are on iOS 8.1 or higher and the older method if we are on iOS 8.0 or older.

enum Errors : ErrorType{

case EmptyData

}

func bytesFromData(data: NSData) throws -> [UInt8]{

if (data.length == 0){

throw Errors.EmptyData

}

var buffer = [UInt8](count: data.length, repeatedValue: 0)

if #available(iOS 8.1, *){

data.getBytes(&buffer, length: data.length)

} else {

data.getBytes(&buffer)

}

return buffer

}

And then we go ahead and call this method:

func example1(){

guard let data = "Foo".dataUsingEncoding(NSUTF8StringEncoding) else {

return

}

do{

let bytes = try bytesFromData(data)

print("Data = \(bytes)")

} catch {

print("Failed to get bytes")

}

}

See Also