简体   繁体   English

调用 URLSession 后我不能做其他工作

[英]I can not do other work after calling URLSession

I just want to hide imageview when the audio starts playing我只想在音频开始播放时隐藏 imageview

URLSession.shared.dataTask(with: serverUrl!) { [self] (data, res, error) in
            do {
                self.myMediaPlayer1 = try AVAudioPlayer(data: data!)
                self.myMediaPlayer1.prepareToPlay()
                self.myMediaPlayer1.delegate = self
                self.SetSessionPlayerOn()
                self.loading_img.isHidden = true    // not work til audio finish playing 
                print("imageview should be hidden now")
                self.myMediaPlayer1.play()
            }catch let error {
                print("error!!!!!!!!!!")
            }
        }.resume()

I can print atone but the image view will be hidden only when the media player has finished playing !我可以打印但只有在媒体播放器播放完毕后才会隐藏图像视图!

UPDATE now it works.现在更新它的工作原理。 thanks Tushar谢谢图沙尔

DispatchQueue.main.async { [unowned self] in
                    self.loading_img.isHidden = true
                }

First, you should update the UI only on the main thread.首先,您应该只在主线程上更新 UI。 So you have to add the below code inside dataTask.因此,您必须在 dataTask 中添加以下代码。 After that, you should update the layout of the view to update the UI.之后,您应该更新视图的布局以更新 UI。 So the code should be like this:所以代码应该是这样的:

URLSession.shared.dataTask(with: serverUrl!) { [self] (data, res, error) in
        do {
            self.myMediaPlayer1 = try AVAudioPlayer(data: data!)
            self.myMediaPlayer1.prepareToPlay()
            self.myMediaPlayer1.delegate = self
            self.SetSessionPlayerOn()
            DispatchQueue.main.async {
                self.loading_img.isHidden = true
                self.view.layoutIfNeeded()
                print("imageview should be hidden now")
            }
            self.myMediaPlayer1.play()
        }catch let error {
            print("error!!!!!!!!!!")
        }
    }.resume()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM