问题描述
当我在 iOS 10 上启动我的应用程序时,两次获得请求通知许可.第一个短暂出现并立即消失而没有允许我做任何动作,然后我得到第二个弹出窗口,其正常行为等待来自的"allow" 或"deny" 用户.
When I launch my app on iOS 10, I get the request notification permission twice.The first one briefly appears and disappears immediately without allowing me to do any actions, then I got the second popup with a normal behaviour waiting for "allow" or "deny" from the user.
这是我的代码,在 iOS 10 之前运行良好.
Here is my code that worked well before iOS 10.
在 AppDelegate 中的 didFinishLaunchingWithOptions 方法中:
if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
#ifdef __IPHONE_8_0
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeBadge
|UIRemoteNotificationTypeSound
|UIRemoteNotificationTypeAlert) categories:nil];
[application registerUserNotificationSettings:settings];
#endif
} else {
UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
[application registerForRemoteNotificationTypes:myTypes];
}
我应该为iOS 10实现一些功能,以解决此双重请求权限吗?
Should I implement something for iOS 10 in order to fix this double request permission ?
推荐答案
对于iOS 10,我们需要在appDelegate didFinishLaunchingWithOptions方法中调用UNUserNotificationCenter.
For iOS 10 we need to call the UNUserNotificationCenter in appDelegate didFinishLaunchingWithOptions method.
首先,我们必须导入UserNotifications框架并在Appdelegate中添加UNUserNotificationCenterDelegate
AppDelegate.h
AppDelegate.h
#import <UIKit/UIKit.h>
#import <UserNotifications/UserNotifications.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate,UNUserNotificationCenterDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
AppDelegate.m
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if([[[UIDevice currentDevice]systemVersion]floatValue]<10.0)
{
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
else
{
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error)
{
if( !error )
{
[[UIApplication sharedApplication] registerForRemoteNotifications];
NSLog( @"Push registration success." );
}
else
{
NSLog( @"Push registration FAILED" );
NSLog( @"ERROR: %@ - %@", error.localizedFailureReason, error.localizedDescription );
NSLog( @"SUGGESTIONS: %@ - %@", error.localizedRecoveryOptions, error.localizedRecoverySuggestion );
}
}];
}
return YES;
}
这篇关于iOS 10请求通知权限触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!