我问用户他们是否允许通知,如果他们同意,我想动画一个勾号。我不确定如何实现这一点,因为权限是异步的,我无法立即检测到结果来执行功能?
这是我当前的代码:
用户点击按钮并触发调用以授予权限并关闭以在完成时勾选按钮
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:
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.
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句