Swift错误"UIButton.currentTitle必须仅从主线程使用" [英] Swift Error "UIButton.currentTitle must be used from main thread only"

查看:66
本文介绍了Swift错误"UIButton.currentTitle必须仅从主线程使用"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

URL:

 导入UIKit导入MediaPlayer类GenreButtonScreen:UIViewController {var musicPlayer = MPMusicPlayerController.applicationMusicPlayer@IBAction func genreButtonTapped(_ sender:UIButton){MPMediaLibrary.requestAuthorization {(状态)在如果状态== .authorized {self.playGenre(类型:sender.currentTitle!)}}}@IBAction func stopButtonTapped(_ sender:UIButton){musicPlayer.stop()}@IBAction func nextButtonTapped(_ sender:UIButton){musicPlayer.skipToNextItem()}func playGenre(genre:String){musicPlayer.stop()让查询= MPMediaQuery()let谓词= MPMediaPropertyPredicate(值:类型,forProperty:MPMediaItemPropertyGenre)查询.addFilterPredicate(predicate)musicPlayer.setQueue(with:query)musicPlayer.shuffleMode = .songsmusicPlayer.play()}} 

解决方案

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

  MPMediaLibrary.requestAuthorization {(状态)在如果状态== .authorized {DispatchQueue.main.async {self.playGenre(类型:sender.currentTitle ?? String())}}} 

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

解决方案

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

这篇关于Swift错误"UIButton.currentTitle必须仅从主线程使用"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆