gpt4 book ai didi

ios - 将完成处理程序添加到函数 swift

转载 作者:行者123 更新时间:2023-12-02 00:07:18 26 4
gpt4 key购买 nike

我有这段代码,它在 Swift 中运行一个音频文件。

 func playSound(name: String) {
DispatchQueue.global(qos: .userInteractive).async {
guard let url = Bundle.main.url(forResource: name, withExtension: "m4a") else {return}
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)

self.player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)

guard let player = self.player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
}

我想向这段代码添加一个完成处理程序。我该怎么做?

最佳答案

只需在声明中添加一个@escaping 参数,然后在任何你想要的地方运行完成闭包(最常见的是成功):

func playSound(name: String, completion: @escaping () -> Void) {  // <- HERE
DispatchQueue.global(qos: .userInteractive).async {
guard let url = Bundle.main.url(forResource: name, withExtension: "m4a") else {return}
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)

self.player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)

guard let player = self.player else { return }
player.play()

completion() // <- HERE
} catch let error {
print(error.localizedDescription)
}
}
}

这样调用它:

let audioPlayer = AudioPlayer()
audioPlayer.playSound(name: "some_sound") {
// Completion closure here gets run (given correct input)
print("Done!")
}

关于ios - 将完成处理程序添加到函数 swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60179108/

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