[英]RequestAuthorization for push outside the didFinishLaunchingWithOptions
对于 ios 10,我用它来注册推送通知:
有没有办法在 appdelegate 和 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool 之外请求 requestAuthorization(options:[.badge, .alert, .sound])
我问的原因是因为我不想在用户使用该应用程序一段时间后显示推送通知的弹出窗口。 有任何想法吗?
就像@dan 说的,没有必要在AppDelegate
请求通知权限。 您可以随心所欲地进行。 这就是您可能正在为此做的事情。
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { (success, error) in
if error == nil {
if success {
print("Permission granted")
// In case you want to register for the remote notifications
let application = UIApplication.shared
application.registerForRemoteNotifications()
} else {
print("Permission denied")
}
} else {
print(error)
}
}
并记住
UserNotifications
框架。AppDelegate
实现didRegisterForRemoteNotificationsWithDeviceToken
方法我的问题是一旦用户同意或拒绝弹出窗口就不会再次显示。 所以我们必须手动将用户重定向到设置。
下面是 Swift 中的代码:
@IBAction func userDidClickButton(_ sender: Any) {
// initialise a pop up for using later
let alertController = UIAlertController(title: "TITLE", message: "Please go to Settings and turn on the permissions", preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
// do something
}
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alertController.addAction(cancelAction)
alertController.addAction(settingsAction)
// check the permission status
UNUserNotificationCenter.current().getNotificationSettings () { settings in
switch settings.authorizationStatus {
case .denied, .notDetermined:
self.present(alertController, animated: true, completion: nil)
case .authorized:
// continue the stuff
DispatchQueue.main.sync {
// Update UI
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.