要在我的库中生成本地通知,我需要使用UserNotification
或UILocalNotification
,具体取决于我的主机应用使用的内容。 (有些客户仍在使用已弃用的didReceiveLocalNotification:
API)。
现在,当我创建通知时,是否可以在运行时确定主机应用使用哪个系统并创建适当的API。这意味着我需要有条件地导入和使用UserNotification
头文件。
修改
关于NSClassFromString
的使用:
if (NSClassFromString(@"FrameworkClass") == nil) {
// the framework is not available
} else {
// the framework is avaiable
}
但我要编写很多UserNotification
代码。我不认为使用performSelector:
会非常实用。
答案 0 :(得分:0)
预处理器宏怎么样?
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000
// Only COMPILE this if compiled against BaseSDK iOS10.0 or greater
#import <UserNotifications/UserNotifications.h>
#endif
答案 1 :(得分:0)
这是注册远程通知检查API的示例
在Swift中
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
在Obj-C
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
} else {
// iOS 10 or later
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
// For iOS 10 display notification (sent via APNS)
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
UNAuthorizationOptions authOptions =
UNAuthorizationOptionAlert
| UNAuthorizationOptionSound
| UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
}];
#endif
}
[[UIApplication sharedApplication] registerForRemoteNotifications];
答案 2 :(得分:0)
我认为你不能在Objective-C中在运行时导入框架。
您可以使用目标c运行时魔术并使用performSelector:来调用选择器/方法而无需导入类/框架但是您不一定要使用它,因为没有编译时检查选择器名称和如果没有使用属性,可能会导致应用程序崩溃。
我能想到实现目标的唯一方法是在您的图书馆中使用weak-link UserNotifications
框架。
在运行时,您可以检查您的客户端是否支持该框架,如果框架符号可用,您可以安全地运行它们。
这样做,您可以获得方法名称检查的编译时安全性,并且您可以以正常方式编写代码,但是在执行任何代码之前,不要忘记检查框架的可用性符号。