Wednesday, May 18, 2016

Objective-C Calling methods based on iOS version

Whenever there is a version change, We need to update our app by taking care of deprecated things and should add the new things in the latest frameworks. For this, We need to call the methods based in iOS versions.

In this post, Let's discuss calling methods based on iOS version of the device in which our app is working. Let me take an WKWebView as example which was introduces in iOS8.

One of WkWebView's properties 'setAllowsLinkPreview' works from iOS9. If we need our WkWebView to handle web links, We need to enable it. But, We can use this only in iOS9. If we use it in lower versions, We will get the below compile time error.



     
[self.wkWebView setAllowsLinkPreview:YES];


No visible @interface for 'WKWebView' declares the selector 'setAllowsLinkPreview:'

To avoid these compile time error, We can take the help of @selector and SEL as shown below.



    
SEL selector = @selector(setAllowsLinkPreview:);

    if([self.wkWebView respondsToSelector:selector]){

        [self.wkWebView performSelector:selector withObject:[NSNumber 
                                                                                   numberWithBool:YES]];
    }


In the above code, I have taken the setAllowsLinkPreview method signature into a SEL object.
I have performed introspection to check whether my WKWebView object responds to this selector or not.

Please check my post Objective C NSObject Root Class to know what are introspection methods.

If it responds, I am performing the selector along with the parameter BOOL object. So, based on iOS version WKWebView responds to the selector.


If we perform selectors like above by checking the whether they responds to that selector or not, We can avoid compile time errors in the above example as well as run time errors also in the case of our custom classes.


Hope this post is useful. Feel free to comment in case of any queries.