ios - 将@available 与存储属性一起使用

标签 ios swift uilocalnotification

我有一个使用本地通知并支持 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/

相关文章:

iphone - 当应用程序处于工作模式时,UILocalNotification 不会触发

ios - Swift 如何检查 TabBarController 中的 ViewController 是否是特定类

ios - setViewControllers 不起作用

swift - 具有结构体静态函数的 GCD

ios - Objective-C:UILocalNotification

ios - Swift - 如何创建首次应用程序启动本地通知?

ios - 在 Atlas.h 中找不到 ATLAddressBarViewController.h

ios - UIActivityIndi​​cator 随 tableView 滚动

ios - 如何从 iPhone/iPad Storyboard迁移到通用 Storyboard

ios - 使用 AFNetworking 3.0 从 URL 设置 TableView Cell 图像(异步)