Swift Error “UIButton.currentTitle must be used from main thread only”

限于喜欢 提交于 2020-01-16 19:01:18

问题


I just followed this you tube tutorial from the following link:

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

I cam across an error saying "UIButton.currentTitle must be used from main thread only"

Not really sure how to fix this as I am new to making apps, can anyone help me?

Greatly appreciated and thanks in advance!

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()
    }
}

回答1:


The MPMediaLibrary.requestAuthorization is an async call, and layout components only can be modified in the Main Thread. You should use this way:

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



回答2:


As the completion of requestAuthorization is in a background thread you need to embed any UIKit code inside the main queue like this

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!) 
            }
        }
    }
}


来源:https://stackoverflow.com/questions/54170821/swift-error-uibutton-currenttitle-must-be-used-from-main-thread-only

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!