gpt4 book ai didi

ios - swift 错误 "UIButton.currentTitle must be used from main thread only"

转载 作者:行者123 更新时间:2023-11-28 13:53:44 25 4
gpt4 key购买 nike

我刚刚从以下链接中学习了这个 you tube 教程:

网址: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()
}
}

最佳答案

MPMediaLibrary.requestAuthorization 是一个异步调用,布局组件只能在主线程中修改。你应该这样使用:

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

关于ios - swift 错误 "UIButton.currentTitle must be used from main thread only",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54170821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com