【问题标题】:Swift: ViewDidLoad does not continue after having accepted notifications permissions requestSwift:接受通知权限请求后 ViewDidLoad 不会继续
【发布时间】:2019-07-07 03:55:38
【问题描述】:

我正在 Swift 中创建一个 iOS 应用程序,在 AppDelegate 中我在 didFinishLaunchingWithOptions 中插入以下代码来询问通知权限

    let center  = UNUserNotificationCenter.current()
    center.delegate = self
    // set the type as sound or badge
    center.requestAuthorization(options: [.sound,.alert,.badge]) { (granted, error) in
        guard granted else { return }
        DispatchQueue.main.async(execute: {
            application.registerForRemoteNotifications()
        })
    }

同时,在 ViewDidLoad 中,我以这种方式询问用户麦克风权限:

    func checkPermission()
{
    switch AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeAudio)
    {
    case .authorized:
        print("ok2")
        self.addButton()
        self.voice()
    case .notDetermined:
        AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeAudio, completionHandler: { granted in
            if granted {
                print("ok1")
                self.addButton()
                self.voice()
            else {
                print("ko")
            }
        })

    case .denied:
        print("ko")
    case .restricted:
        return
    }
}

问题是: 接受麦克风权限后,我接受了通知权限,但之后,ViewController 中的代码没有继续执行(方法 addButton 和 voice 没有执行)。

你能帮帮我吗? 提前非常感谢您

【问题讨论】:

  • 您是否尝试在viewWillAppearviewDidAppear而不是viewDidLoad中调用checkPermission()?您在这里遇到同样的问题吗?
  • 会打印“ok1”吗?
  • @AndreasOetjen 是的,打印了“ok1”
  • 如果 ok1 被打印,那么它们应该被调用,你调试了吗?
  • @Teetz 不,我没有尝试过。也许如果我在 viewWillAppear 中调用该函数,它将起作用。我会试试看。谢谢

标签: ios swift notifications microphone


【解决方案1】:

可能问题是由线程问题引起的:AVCaptureDevice.requestAccess 中的完成处理程序在任意工作线程中执行。如果你在这里做 UI 的东西(比如添加一个按钮),这必须在主线程中完成,例如

AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeAudio) { granted in
    if granted {
        print("ok1")
        DispatchQueue.main.async { [unowned self] in
            self.addButton()
            self.voice()
        }            
    else {
        print ("ko")
    }
}

但我想知道为什么 UIKit 在你的情况下不会崩溃(或至少抱怨)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    相关资源
    最近更新 更多