我正在使用Swift编写应用程序,我需要显示alert .应用程序必须与iOS 7和iOS 8兼容.既然UIAlertView已被UIAlertController取代,我如何在不判断系统版本的情况下判断UIAlertController是否可用?我一直听说苹果建议我们不要为了确定API的可用性而判断设备的系统版本.

这是我在iOS 8上使用的,但在iOS 7上,它会以"dyld: Symbol not found: _OBJC_CLASS_$_UIAlertAction"崩溃:

let alert = UIAlertController(title: "Error", message: message, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "OK", style: .Cancel, handler: nil)
alert.addAction(cancelAction)
presentViewController(alert, animated: true, completion: nil)

如果我在iOS 8上使用UIAlertView,我会收到以下警告:Warning: Attempt to dismiss from view controller <_UIAlertShimPresentingViewController: 0x7bf72d60> while a presentation or dismiss is in progress!

推荐答案

检测模式与Objective-C样式相同.

您需要检测当前活动运行时是否能够实例化此类

if objc_getClass("UIAlertController") != nil {

     println("UIAlertController can be instantiated")

      //make and use a UIAlertController

 }
 else {

      println("UIAlertController can NOT be instantiated")

      //make and use a UIAlertView
}

不要试图根据操作系统版本来解决这个问题.你需要检测NOT个操作系统的能力.

EDIT

这个答案NSClassFromString("UIAlertController")的原始探测器在-O优化下失败,因此它被更改为当前版本,该版本适用于发布版本

EDIT 2

NSClassFromString正在Xcode 6.3/Swift 1.2中进行所有优化

Swift相关问答推荐

";async let和";async之间的差异让我们等待";

Swift:iVar + Equatable上的协议约束

如何为任务扩展的泛型静态函数获得自动类型推理

SwiftUI正在初始化不带状态变量的绑定变量

将NavigationSplitView更改为NavigationStack

如何在macOS中延迟退出应用程序的退出操作?

如何为我的项目设置生命周期选项?

SwiftUI路径平滑连接两条线

UIBezierPath() 和 DragGesture:连接点创建角而不是曲线

如何在闭包中使用构造 await sync

当使用 CGFloat 而不是数字文字时,为什么 node 的位置会发生变化?

Vapor 4 身份验证问题 [用户未通过身份验证]

将 struct 作为泛型类型传递并访问该泛型类型属性

如何从元组数组创建字典?

由于编译器中的内部保护级别,无法访问框架 init 中的公共 struct

DispatchQueue:不能在非主线程上使用 asCopy = NO 调用

如何使用 swift 在 tableview 中填充两个不同数组的两个部分?

Void 函数中意外的非 Void 返回值 (Swift 2.0)

如何使用 Swift 将文本文件逐行加载到数组中?

Swift performSegueWithIdentifier 不起作用