iosswift2watchoswatchos-2

Detecting available API iOS vs. watchOS in Swift


#available does not seem to work when differentiating between watchOS and iOS.

Here is an example of code shared between iOS & watchOS:

lazy var session: WCSession = {
    let session = WCSession.defaultSession()
    session.delegate = self
    return session
}()

...

if #available(iOS 9.0, *) {
    guard session.paired else { throw WatchBridgeError.NotPaired } // paired is not available
    guard session.watchAppInstalled else { throw WatchBridgeError.NoWatchApp } // watchAppInstalled is not available
}

guard session.reachable else { throw WatchBridgeError.NoConnection }

Seems that it just defaults to WatchOS and the #available is not considered by the compiler.

Am I misusing this API or is there any other way to differentiate in code between iOS and WatchOS?

Update: Seems like I was misusing the API as mentioned by BPCorp

Using Tali's solution for above code works:

    #if os(iOS)
        guard session.paired else { throw WatchBridgeError.NotPaired }
        guard session.watchAppInstalled else { throw WatchBridgeError.NoWatchApp }
    #endif

    guard session.reachable else { throw WatchBridgeError.NoConnection } 

Unfortunately there is no #if os(watchOS) .. as of Xcode 7 GM

Edit: Not sure when it was added but you can now do #if os(watchOS) on Xcode 7.2


Solution

  • If you want to execute that code only on iOS, then use #if os(iOS) instead of the if #available(iOS ...).

    This way, you are not using a dynamic check for the version of your operating system, but are compiling a different code for one OS or the other.