Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 817
Cezar Avatar asked Sep 01 '15 22:09

Cezar


2 Answers

In the Apple dev guide, it is said that the star, * (which is required) means that it will execute the if body for OSes not specified but listed in the minimum deployment target specified by your target.

So, if your target specifies iOS and watchOS, your statement if #available(iOS 9.0, *) means that the ifbody is available for iOS 9 and later and any watchOS version.

Also, be careful if you want to use what's described in the chapter "Build Configurations" in this Apple guide. It is used to conditionally compile your code based on the operating system. This is not dynamic at runtime.

like image 37
BPCorp Avatar answered Sep 28 '22 17:09

BPCorp


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.

like image 198
Tali Avatar answered Sep 28 '22 17:09

Tali