Search code examples
swiftapple-watch

Implement WatchConnectivity in an iOS App that supports iOS 8.0


My current iOS App supports iOS 8 and greater. I decided to implement a Watch App and I want to have watch and iOS app comunicate via WatchConnectivity. Let's say that I want to build a class to handle the connectivity and this class is a WCSessionDelegate. To be able to include the class in my project I've to wrap it into the @available(iOS 9.0,0) tag and that's ok...but, how can I keep track of an instance of this class in the AppDelegate (or in any other class)??? I cannot write something like

class AppDelegate: UIResponder, UIApplicationDelegate {
    @available(iOS 9.0,0)
    var connectivityHandler: ConnectivityHandler?

How can I use these class in a project that should support also iOS 8?!

Edit---- I've found this solution but it doesn't sound really "good". I create a dynamic property and dependently on the current system I return a instance or just nil... the property should obviously be of type AnyObject to be a valid iOS8 parameter...

var _connectivityHandler: AnyObject?
var connectivityHandler: AnyObject? {
    get {
        if _connectivityHandler != nil {
            return _connectivityHandler
        }else{
            if #available(iOS 9.0, *) {
                _connectivityHandler = ConnectivityHandler()
            } else {
                _connectivityHandler = nil
            }
            return _connectivityHandler
        }
    }
    set(value) {
        _connectivityHandler = value
    }
}

Solution

  • You can move all the WatchConnectivity functions in your connectivityHandler to an extension of that class and mask that with the @availability API:

    import UIKit
    import WatchConnectivity
    
    class ConnectivityHandler: NSObject {
    
    }
    
    @available(iOS 9.0, *)
    extension ConnectivityHandler: WCSessionDelegate {
        func initSession() {
            if WCSession.isSupported() {
                let session = WCSession.defaultSession()
                session.delegate = self
                session.activateSession()
            }
        }
    }
    

    If you do that you can add this class to your AppDelegate and it also compiles in iOS 8:

    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
        var window: UIWindow?
        let connectivityHandler = ConnectivityHandler()
        ....
    }