推送权限的申请
- 加入头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
申请权限
-(void) requestNotification
{
if (@available(iOS 10, *))
{
UNUserNotificationCenter * center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted) {
// 允许推送
}else{
//不允许
}
}];
}
else if(@available(iOS 8 , *))
{
UIApplication * application = [UIApplication sharedApplication];
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil]];
[application registerForRemoteNotifications];
}
else
{
UIApplication * application = [UIApplication sharedApplication];
[application registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];
[application registerForRemoteNotifications];
}
}
查看当前的权限
-(void) checkCurrentNotificationStatus
{
if (@available(iOS 10 , *))
{
[[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
if (settings.authorizationStatus == UNAuthorizationStatusDenied)
{
// 没权限
}
}];
}
else if (@available(iOS 8 , *))
{
UIUserNotificationSettings * setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
if (setting.types == UIUserNotificationTypeNone) {
// 没权限
}
}
else
{
UIRemoteNotificationType type = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (type == UIUserNotificationTypeNone)
{
// 没权限
}
}
}
没权限进入设置页面
#pragma mark 没权限的弹窗
-(void) showAlrtToSetting
{
UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"您还没有允许****权限" message:@"去设置一下吧" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}];
UIAlertAction * setAction = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
dispatch_async(dispatch_get_main_queue(), ^{
if ([[UIApplication sharedApplication] canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url];
}
});
}];
[alert addAction:cancelAction];
[alert addAction:setAction];
[self presentViewController:alert animated:YES completion:nil];
}
如有瑕疵之处,望大家不吝指教