我询问用户是否允许通知,然后如果他们同意,我想制作一个勾号动画。我不确定如何实现这一点,因为权限是异步的,我无法立即检测到结果来执行功能?
这是我当前的代码:
用户点击按钮并触发调用以授予权限,并在完成时关闭以勾选按钮
func userDidTapNotifications() {
self.appDelegate.setupNotifications { (success) -> Void in
if success {
notificationsGranted()
}
}
}
函数显示批准弹出窗口并完成关闭,问题是它会在用户选择异步选项之前完成,所以我在用户授予访问权限之前完成 true,导致问题。
func setupNotifications(completion: (_ success: Bool) -> Void) {
center.requestAuthorization(options: [.badge, .alert , .sound]) { (granted, error) in
if granted {
DispatchQueue.main.async(execute: {
UIApplication.shared.registerForRemoteNotifications()
})
}
}
completion(true)
}
在此之后我在关闭完成时调用我的最终函数:
func notificationsGranted() {
let isRegisteredForRemoteNotifications = UIApplication.shared.isRegisteredForRemoteNotifications
if isRegisteredForRemoteNotifications {
self.permissionsView.notificationsSwitch.setSelected(true, animated: true)
self.userDefaults.set(true, forKey: "notificationsApproved")
arePermissionsGranted()
}
}
呈现权限警报然后根据响应采取行动的正确方法是什么?
最佳答案
将完成处理程序存储在 AppDelegate
的全局对象中,当调用 didRegisterRemoteNotification
方法时,只需调用已存储的完成处理程序...
在您的 ViewController
中,您应该调用 setUpNotification
方法。
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var notificationCompletion: ((Bool)->Void)?
func setUpNotification(completion: @escaping (Bool)->Void) {
self.notificationCompletion = completion //Store the completion in a global property to use later.
//Invoke Your Notification Registration methods...
//Do not invoke the completion handle here...
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
//Permission is granted. Now invoke the completion that you have store to use later.
if let completion = self.notificationCompletion {
completion(true)
}
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
//Permission is not granted/failed. Now invoke the completion that you have store to use later.
if let completion = self.notificationCompletion {
completion(false)
}
}
}
ViewController.swift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
appDelegate.setUpNotification(completion: { isPermissionGranted in
if isPermissionGranted {
DispatchQueue.main.async {
self.notificationPermissionIsGranted()
}
}
})
}
}
func notificationPermissionIsGranted() {
//Animate Your View..
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
关于ios - 对用户权限授予结果执行功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47348315/