Search code examples
iosswiftwatchkitwatchconnectivity

How to integrate `Watch Connectivity` safely only for iOS 9 users with the App which is still having iOS7 as minimum development target?


I am currently working on an App which is still supporting iOS 7 (minimum development target), but I got a requirement to integrate Watch Connectivity only for the users who are using iOS 9. Therefore I created a singleton named WatchConnectivityManager and it is having a private member like this.

private let session: WCSession? = WCSession.isSupported() ? WCSession.defaultSession() : nil

Everything works fine on iOS 9 but with iOS 8 and 7 I am getting crash exactly on the above line even though my WatchConnectivityManager singleton class definition starts as follows.

@available(iOS 9.0, *)
class WatchConnectivityManager: NSObject, WCSessionDelegate {
    ....
}

Any help to overcome this situation will be appreciated.

NB: I can easily perform version check allover the places where I am using WCSession related code. But is there any way to integrate that check only inside the WatchConnectivityManager singleton implementation?


Solution

  • Finally I found the answer which is simply adding

    NSClassFromString("WCSession") != nil
    

    check before any usage of WCSessionclass like this.

    private let session: WCSession? = NSClassFromString("WCSession") != nil && WCSession.isSupported() ? WCSession.defaultSession() : nil
    

    Any more better answers?