问题描述
#available
似乎不起作用。
以下是一个示例iOS和iOS之间共享的代码watchOS:
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 }
似乎它默认为WatchOS和 #available 。
Seems that it just defaults to WatchOS and the
#available
is not considered by the compiler.
我是否滥用此API或是否有其他方法可以区分iOS和WatchOS之间的代码?
Am I misusing this API or is there any other way to differentiate in code between iOS and WatchOS?
更新:似乎我误用了BPCorp提到的API
使用Tali的解决方案代替上述代码工作原理:
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 }
不幸的是没有
#if os(watchOS)
..从Xcode 7 GM开始
Unfortunately there is no
#if os(watchOS)
.. as of Xcode 7 GM
编辑:不确定何时添加,但您现在可以在Xcode 7.2上执行
#if os(watchOS)
Not sure when it was added but you can now do
#if os(watchOS)
on Xcode 7.2
推荐答案
如果您只想在iOS上执行该代码,请使用
#if os(iOS)
而不是如果#available(iOS ...)
。
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.
这篇关于在Swift中检测可用的API iOS与watchOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!