Swift 3和Xcode 8.2中的用户通知的条件编译 [英] Conditional Compilation for User Notifications in Swift 3 and Xcode 8.2
问题描述
我们有一个支持iOS 9+的应用程序,该应用程序正在Swift 3和Xcode 8.2.x中开发.iOS 10引入了一种注册推送通知的新方法,描述得很好 #available
产生相似的结果
定位通用/真实设备时就是这种情况.该应用程序将针对模拟器进行编译.
根据上面的评论,您需要运行时检查,而不是条件编译,而 #available
正是这样.
这对我来说很好:
如果#available(iOS 10.0,*){UNUserNotificationCenter.current().requestAuthorization(选项:[.badge,.alert,.sound]){(已授予,错误)在}}别的 {UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(类型:[.badge,.sound,.alert],类别:nil))}
UIUserNotificationSettings
在iOS 10中已弃用,但实际上仍然存在.苹果通常不会删除API,直到很长一段时间不推荐使用它们.
我怀疑您还有其他构建问题.让我烦恼的是:您是否正确设置了Base SDK和Deployment Target?
We have an application supporting iOS 9+, that is being developed in Swift 3 and Xcode 8.2.x. iOS 10 introduced a new method for registering for push notifications, described well in this post. Since iOS 9 doesn't know about the User Notifications framework, we want to use the iOS 9 method when the device is iOS 9, and use the UserNotifications.framework
on iOS 10. In Objective C, we would accomplish this via conditional compilation (e.g. #ifdef
statements).
In Swift 3, there is some facility for conditional compilation #available
and #if
. We try to wrap the branches of notification registration code in either of these directives, and the app will not compile.
#available
generates similar results
This is the case when targeting generic/real devices. The app will compile against simulators.
Based on your comments above, you want a runtime check, not conditional compilation, and #available
is precisely that.
This works fine for me:
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .alert, .sound]) {
(granted, error) in
}
}
else {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
}
UIUserNotificationSettings
is deprecated in iOS 10, but it's actually still there. Apple doesn't typically remove APIs until they've been deprecated for a very long time.
I suspect you have some other kind of build issue. Off the top of my head: do you have Base SDK and Deployment Target set correctly?
这篇关于Swift 3和Xcode 8.2中的用户通知的条件编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!