Monday, September 29, 2014

Swift - Checking if a method exists

A lot of changes has happened in iOS 8, and a lot of APIs require that you call certain new methods before they can work. Examples are locations, notifications, and more.

To ensure that your app can work on older versions of iOS as well as the new iOS 8, it is important that you only call the new API when your app is running on iOS 8. The best way is to test if a method exists. You can do so via the respondsToSelector() method. The following example tests to see if the UIApplication object contains the registerUserNotificationSettings() method:

if application.respondsToSelector("registerUserNotificationSettings") {

}

Another example:

if self.locationManager.respondsToSelector("requestAlwaysAuthorization") {


}

No comments: