推送權限的申請
- 加入頭文件
#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];
}
如有瑕疵之處,望大家不吝指教