问题
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