Swift错误“ UIButton.currentTitle必须仅在主线程中使用”

时间:2019-01-13 16:24:44

标签: ios swift uibutton

我刚刚通过以下链接关注了您的教程:

URL:https://www.youtube.com/watch?v=aiXvvL1wNUc

我遇到一个错误,提示“ UIButton.currentTitle必须仅在主线程中使用”

由于我是制作应用程序的新手,所以不太确定如何解决此问题,有人可以帮助我吗?

非常感谢,并提前致谢!

enter image description here

import UIKit
import MediaPlayer

class GenreButtonScreen: UIViewController {
    var musicPlayer = MPMusicPlayerController.applicationMusicPlayer

    @IBAction func genreButtonTapped(_ sender: UIButton) {
        MPMediaLibrary.requestAuthorization { (status) in
            if status == .authorized {
                self.playGenre(genre: sender.currentTitle!)
            }
        }
    }

    @IBAction func stopButtonTapped(_ sender: UIButton) {
        musicPlayer.stop()
    }

    @IBAction func nextButtonTapped(_ sender: UIButton) {
        musicPlayer.skipToNextItem()
    }

    func playGenre(genre:String) {
        musicPlayer.stop()

        let query = MPMediaQuery()
        let predicate = MPMediaPropertyPredicate(value: genre, forProperty: MPMediaItemPropertyGenre)

        query .addFilterPredicate(predicate)

        musicPlayer.setQueue(with: query)
        musicPlayer.shuffleMode = .songs 
        musicPlayer.play()
    }
}

2 个答案:

答案 0 :(得分:1)

MPMediaLibrary.requestAuthorization是一个异步调用,并且只能在主线程中修改布局组件。您应该使用这种方式:

 MPMediaLibrary.requestAuthorization { (status) in
    if status == .authorized {
        DispatchQueue.main.async { 
           self.playGenre(genre: sender.currentTitle ?? String()) 
        }
    }
}

答案 1 :(得分:0)

由于requestAuthorization的完成是在后台线程中,因此您需要像这样

一样在主队列中嵌入任何 UIKit 代码
DispatchQueue.main.async { 
  self.playGenre(genre: sender.currentTitle!) 
}

@IBAction func genreButtonTapped(_ sender: UIButton) {
    MPMediaLibrary.requestAuthorization { (status) in
        if status == .authorized {
            DispatchQueue.main.async {
              self.playGenre(genre: sender.currentTitle!) 
            }
        }
    }
}