我有一个包含用户“警报”的iOS应用-当该应用不在前台时发送给用户。我正在使用UNUserNotifications,并且在iOS 10和iOS 11测试中一切正常。
我也想接触仍在使用iOS 8和iOS 9的用户。
为了向iOS 8用户发送通知,我是否需要包括使用UILocalNotifications的替代方法?还是iOS 8会正确响应UNUserNotificatons?
如果需要同时包含两者,则可以使用某些if来基于OS使用正确的选项。我必须包含不推荐使用的技术,这似乎很奇怪。
最佳答案
UNUserNotifications
是iOS 10及更高版本,因此无法在iOS 8和iOS 9上运行。在这种情况下,您应该检查UNUserNotifications
是否存在,否则应使用较旧的方法,例如:
if (NSClassFromString(@"UNUserNotificationCenter")) {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
UNAuthorizationOptions options = (UNAuthorizationOptionBadge | UNAuthorizationOptionAlert | UNAuthorizationOptionSound);
[center requestAuthorizationWithOptions: options
completionHandler: ^(BOOL granted, NSError * _Nullable error) {
if (granted) {
NSLog(@"Granted notifications!");
}
}];
}
else {
UIUserNotificationType userNotificationTypes = (UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound);
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes: userNotificationTypes categories: nil];
[[UIApplication sharedApplication] registerUserNotificationSettings: settings];
}