我有一个使用本地通知并支持 iOS 10 的应用程序。我正在尝试添加 iOS 9 支持,这需要我使用旧的位置通知 API。我正在尝试在我的 iOS 10 代码上使用 @available
和 #available
但我不知道如何让我的 center 变量仅适用于运行 iOS 10 的设备.
当我将目标从 iOS 10 设置为 9 时,我收到此变量的错误消息:
UNUserNotificationCenter is only available on iOS 10.0 or newer.
它建议我将 @available(iOS 10.0, *)
添加到我的整个类中,我不想这样做,因为此类中有代码将用于 iOS 9。我感谢有关如何将我的中心属性限制为仅 iOS 10 的任何建议。
class ViewController: UIViewController, UITextFieldDelegate {
let center = UNUserNotificationCenter.current()
...
}
最佳答案
适用于 Xcode 14(及更低版本)的解决方案
这是一个可能的解决方案(感谢 blog post )。这个想法是使用类型为 Any
的存储属性,然后创建一个计算属性来转换存储属性(并在必要时实例化它)。
private var _selectionFeedbackGenerator: Any? = nil
@available(iOS 10.0, *)
fileprivate var selectionFeedbackGenerator: UISelectionFeedbackGenerator {
if _selectionFeedbackGenerator == nil {
_selectionFeedbackGenerator = UISelectionFeedbackGenerator()
}
return _selectionFeedbackGenerator as! UISelectionFeedbackGenerator
}
关于ios - 将@available 与存储属性一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41904724/