如何在Swift 4中按顺序执行操作

时间:2018-05-17 11:45:52

标签: ios swift

我目前正在开发一款只有图片和图片的简单应用。一个按钮。按下按钮时,将播放声音并打开网页。我希望在打开网页之前先播放声音。我怎样才能做到这一点?这是我的代码:

@IBAction func webButton(_ sender: UIButton) {

    let Bismillah = NSURL(fileURLWithPath: Bundle.main.path(forResource: "Basmalah", ofType: "mp3")!)
    do {
        audioPlayer = try AVAudioPlayer(contentsOf: Bismillah as URL)
        audioPlayer.prepareToPlay()
    } catch {
        print("Problem in getting File")
    }
    audioPlayer.play()


    if let url = URL(string: "http:/donate.edialoguec.com/campaign/details/63") {
        UIApplication.shared.open(url, options: [:])
    }
}

2 个答案:

答案 0 :(得分:0)

你可以尝试

audioPlayer.play()
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
   if let url = URL(string: "http:/donate.edialoguec.com/campaign/details/63")  {
     UIApplication.shared.open(url, options: [:])
   }
 }

答案 1 :(得分:0)

如果延迟时间> =声音的持续时间,则使用后调度将起作用。 要完全实现目标,您需要设置audioPlayer.delegate = self并实施此方法。 https://developer.apple.com/documentation/avfoundation/avaudioplayerdelegate/1389160-audioplayerdidfinishplaying 当玩家完成游戏时,该方法将被调用,您可以在此时打开网页。