【问题标题】:Compile-time test for availability of UIApplication.shared?UIApplication.shared 可用性的编译时测试?
【发布时间】:2018-06-18 20:23:38
【问题描述】:

我有一些共享代码需要在 iOS 应用应用扩展中工作,并且需要设置 UIApplication.shared.isNetworkActivityIndicatorVisible — 但前提是代码在应用中使用。

在应用扩展中,UIApplication.shared 给出了以下编译错误:

'shared' is unavailable: Use view controller based solutions where appropriate instead

没关系;我不想想要在应用扩展中使用它。但是,我找不到在编译时禁用该代码的方法。可悲的是,if #available 似乎没有奏效。它关闭了代码路径,但编译器仍然不喜欢它:

if #available(iOSApplicationExtension 0, *) {
    print("This is an extension")
} else {
    print("This is an app")
    print(UIApplication.shared)  // Unreachable in extension, but still doesn’t compile
}

我没有看到任何处理此问题的 #if 检查。

在 Swift 中有什么方法可以有条件地编译需要 UIApplication.shared 的代码吗?

【问题讨论】:

  • 您需要重构您的代码,以便使用扩展中不允许的任何 API 的任何代码都不会针对该扩展。
  • 为应用程序和扩展程序提供服务的 CocoaPod 无法做到这一点。
  • 您找到解决方案了吗?
  • @fruitcoder 不,对不起。

标签: ios swift swift4


【解决方案1】:

一种可能的解决方案是避免显式使用UIApplication.shared,而是使用Objective-C 选择器包装。

这是一个可能有帮助的扩展(基于https://github.com/ephread/Instructions/issues/21

extension UIApplication {
    static var safeShared: UIApplication? {
        guard UIApplication.responds(to: Selector(("sharedApplication"))) else {
            return nil
        }

        guard let unmanagedSharedApplication = UIApplication.perform(Selector(("sharedApplication"))) else {
            return nil
        }

        return unmanagedSharedApplication.takeRetainedValue() as? UIApplication
    }
}

用法

if let app = UIApplication.safeShared {
    result = app.applicationState == .active
}

快乐编码?‍?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-27
    • 2021-03-04
    • 1970-01-01
    • 2016-03-19
    • 1970-01-01
    相关资源
    最近更新 更多