How to ask for remote permission in iOS 10/Swift 3

旧街凉风 提交于 2019-12-25 04:27:39

问题


I want to ask the user for permissions (remote and local notifications, camera and audio) from a separate viewController. The viewcontroller will be presented during the onboarding process, and never again.

How can I ask for permissions to display remote notifications outside the AppDelegate? My question is not how to trigger them, but how to make sure that the AppDelegate is "responsible" for handling them once a permission have been granted.

Current code in AppDelegate

import UIKit
import UserNotifications
import PushKit
import CallKit


AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, UNUserNotificationCenterDelegate {

let pushRegistry = PKPushRegistry(queue: DispatchQueue.main)

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    pushRegistry.delegate = self
    pushRegistry.desiredPushTypes = [.voIP]


    ....

}

ViewController where I ask for permission

import UIKit
import UserNotifications


class AskForNotificationPermissionVC: UIViewController{

    override func viewDidLoad() {
        super.viewDidLoad()

        requestPermissions { (videoGranted, audioGranted, notificationsGranted) in
            if videoGranted && audioGranted && notificationsGranted {
                DispatchQueue.main.async{
                    self.performSegue(withIdentifier: "toPaySegue", sender: self)
                }
            } else {
                DispatchQueue.main.async{
                    self.presentSpecialPopoup()
                }
             }
        }
     }




    func requestPermissions (completion: @escaping ((Bool, Bool, Bool)->())) {
        let center = UNUserNotificationCenter.current()
        center.delegate = UIApplication.shared.delegate as! UNUserNotificationCenterDelegate?

        AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (videoGranted: Bool) -> Void in
            AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeAudio, completionHandler: { (audioGranted: Bool) -> Void in
                center.requestAuthorization(options: [.alert, .badge, .sound]) { (notificationGranted:Bool, error) -> Void in
                    UIApplication.shared.registerForRemoteNotifications()
                    completion(videoGranted, audioGranted, notificationGranted)
                }
            })
        })
    }
}

Any help is very, very much appreciated !! Thank you.


回答1:


UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
    //handle result
}


来源:https://stackoverflow.com/questions/40587598/how-to-ask-for-remote-permission-in-ios-10-swift-3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!