我想在我的Swift iOS应用程序中使用NSURLQueryItem.但是,该类仅在iOS 8中可用,但我的应用程序也应该在iOS 7上运行.如何在Swift中检查类是否存在?
在Objective-C中,您可以执行以下操作:
if ([NSURLQueryItem class]) {
// Use NSURLQueryItem class
} else {
// NSURLQueryItem is not available
}
Run Code Online (Sandbox Code Playgroud)
与此问题相关的是:如何检查现有类的方法或属性是否存在?
在https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/AdvancedAppTricks/AdvancedAppTricks.html#//apple_ref/doc/uid/TP40007072-CH7-SW4中有一个很好的部分称为支持多个iOS的版本,解释了Objective-C的不同技术.如何将这些转换为Swift?
我正进入(状态
yld: Symbol not found: _OBJC_CLASS_$_UIUserNotificationSettings
Run Code Online (Sandbox Code Playgroud)
这是当应用程序在iOS7设备上运行时甚至根本没有在代码中调用该函数时导致错误的函数.
Run Code Online (Sandbox Code Playgroud)func reigsterForRemoteUserNotifications(notificationTypes: UIUserNotificationType, categories: NSSet) { let userNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: categories) (UIApplication.sharedApplication()).registerUserNotificationSettings(userNotificationSettings) UIApplication.sharedApplication().registerForRemoteNotifications() }
我不希望在iOS7设备上运行时可以访问此方法.我不希望在其中进行选择检查,因为这意味着该方法可用于开始.
我想要的是一个构建配置参数来检查版本:我无法找到一种方法来编写一个快速等效的预处理器宏来检查正确的iOS版本并忽略新的和未声明的iOS 8库函数.
#if giOS8OrGreater
// declare the functions that are iOS 8 specific
#else
// declare the functions that are iOS 7 specific
#endif
Run Code Online (Sandbox Code Playgroud)
在文档中,apple建议使用函数和泛型来替换复杂的宏,但在这种情况下,我需要构建配置预编译检查以避免处理未声明的函数.有什么建议.
我的应用程序使用UIBlurEffect,但旧设备(特别是iPad 2和3,支持iOS 8)没有模糊支持.
我想检查用户的设备是否支持模糊.我该怎么做?
在 macOS 上,我使用必须由用户安装的外部框架(用 C 编写)。在 Swift 中,我需要在运行时检查它是否存在,并且我不能使用 #available() 因为它用于与操作系统相关的功能,并且我正在尝试追踪外部框架。另外,NSClassFromString() 没有用,因为它不是 Objective-C 框架。
我一直在尝试了解如何复制 Objective-C 等效项来检查弱链接符号,例如:
if ( anExternalFunction == NULL ) {
// fail graciously
} else {
// do my thing
}
Run Code Online (Sandbox Code Playgroud)
但在 Swift 中,这似乎不起作用:编译器指出,由于 anExternalFunction 不是可选的,所以我总是会得到 != nil,这使得“Swift 有意义”,但对我没有一点帮助。
我找到了两种解决方案,但它们让我的代码变得很糟糕,就像你不会相信的那样:
选项 1,使用名为 isFrameworkAvailable() 的函数创建一个 Objective-C 文件来完成工作,并从 Swift 调用
选项 2,使用以下 Swift 代码实际检查库:
let libHandle = dlopen("/Library/Frameworks/TheLib.framework/TheLib", RTLD_NOW)
if (libHandle != nil) {
if dlsym(libHandle, "anExternalFunction") != nil {
return true
}
}
return false
Run Code Online (Sandbox Code Playgroud)
我一直无法让选项 2 与 RTLD_DEFAULT …
swift ×5
ios ×4
dll ×1
dlsym ×1
frameworks ×1
macros ×1
swift3 ×1
uiblureffect ×1
weak-linking ×1