您可以将用户发送到用户设备设置应用的应用设置页面,让他们选择加入 LocalNotification
- 版本 10 之前的 iOS 不提供用户之前是否拒绝权限的信息。
- 在您的应用中,您需要保存在 NSUserDefaults 或您已经请求权限的地方。
- 每次需要权限时,首先检查权限是否可用。
- 如果权限不可用并且您的应用之前没有询问过用户(基于上一步中保存的状态),您可以请求权限。
- 如果您之前已向用户征求过许可(根据上一步中保存的状态),您会提示用户是否要允许许可,如果他们说“是”,则将其转发到设备设置应用程序。
适用于 iOS
这是一些查询UIUserNotificationSettings的代码片段
UIUserNotificationSettings *currentSettings = [[UIApplication sharedApplication] currentUserNotificationSettings]
if (currentSettings.types == UIUserNotificationTypeNone) // Permission does not exist either user denied or never been asked before
if (!(currentSettings.types & (UIUserNotificationTypeAlert | UIUserNotificationTypeSound))) // This means your app does not have permission alert and to play sounds with notification.
此代码片段显示如何将用户发送到设备设置页面。
NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
if ([[UIApplication sharedApplication] canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url];
}
Swift 3 for iOS
这是一些查询UIUserNotificationSettings的代码片段
let currentSettings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
if currentSettings.types.isEmpty {
// Here you decide whether to prompt user with new authorization request
// or send user to setting app based on your stored variable
}
此代码片段展示了如何将用户发送到设备设置页面。
if let urlStr = URL(string: UIApplicationOpenSettingsURLString) {
if UIApplication.shared.canOpenURL(urlStr) {
UIApplication.shared.openURL(urlStr)
}
}
适用于 iOS 10 及更高版本
检查您的应用是否曾要求授权,而不是在您的应用中保存变量,而是检查 UNNotificationSettings 类的 authorizationStatus 的值
如果您的应用从未使用 requestAuthorization(options:completionHandler:) 方法请求授权,则此属性的值未确定。
以及与此类的旧版本 (UIUserNotificationSettings) 类似的其他 UNNotificationSettings 对应方法请求权限或检查可用权限,如徽章、警报或声音。