问题
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