MPMediaLibrary requestAuthorization 在用户接受权限后执行代码,即使在使用完成处理程序之后

MPMediaLibrary requestAuthorization does execute the code after user accept the permission , Even after using completion handler

在此处输入代码我有这样的权限处理程序代码:

func authorizeMediaLibrary(forStatus status: MPMediaLibraryAuthorizationStatus) -> Void{
    switch status {
    case .authorized:
           self.initializeMedia()
    case .denied:
        guard let settingUrl = URL(string: UIApplication.openSettingsURLString) else {return}
        if UIApplication.shared.canOpenURL(settingUrl) {
            UIApplication.shared.open(settingUrl) { success in}
        }
    case .notDetermined:
        MPMediaLibrary.requestAuthorization { stat -> Void in
       
            if stat == .authorized {
                self.media.getMediaQueryCollection()
                self.allMediaItems = self.media.getMPMediaItemCollection()

            }
        }
    default:
       break
    }
    
}

我什至试过这个:

func getAuthrization(completionHandler:@escaping (Bool) -> Void)  {
            if MPMediaLibrary.authorizationStatus() == .authorized {
                completionHandler(true)
            } else {
                MPMediaLibrary.requestAuthorization() { completionHandler([=11=] == .authorized) }
            }
        } 

但是他们两个都没有帮助我,弹出窗口会显示,但是接受后,它不会调用回调并且不会刷新我的视图来填充 data.I 知道它是关于刷新我的从我的理解来看,因为当我再次 运行 时,我得到了结果并且权限状态更改为授权。

问题:

你遇到的问题与重新加载数据有关,因为我从你的代码中看到授权配置正确,所以我建议在视图控制器的生命周期方法中刷新数据,并调用viewWillAppear(_ animated: Bool) 函数中的授权请求,这里是我给你的推荐

 override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        authorizeMediaLibrary(forStatus: 
        MPMediaLibrary.authorizationStatus())
        //initialize your code for fetching the music data here.
       // reload your view , for example if you are showing it in tableview  
 use something like this, *self.tableview.reloadData()*
        if mediaItemFetched.count < 1 {
            timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector:     #selector(self.refreshItem(), userInfo: nil, repeats: true)
            
        }
    }

这里我所做的是添加计时器以在第二个时间间隔内检查数据,因此在该 scheduledTimer 中我具有选择器功能来刷新数据存储或数据项,如果数据不存在,我将在其中重新初始化数据,然后我使计时器无效并刷新我的视图。我已经用简单的随机数据实现对其进行了测试,它对我有用,我使用你的函数来请求授权。