ryohei ryohei - 11 months ago 27
Swift Question

How to activate a function after a given time?

I would like to activate a function after a sound is played and complete. I assume that NSTimer needs to be included, but I am not sure of how to implement in order to make it. It is helpful if you could give me some code that works.


You should post code that you tried, and then someone then can help you make the code work. In this case, you don't need a timer for what you're doing. The AVAudioPlayerDelegate protocol on the player was designed for what you are trying to do:

import UIKit
import AVFoundation

class ViewController: UIViewController, AVAudioPlayerDelegate {

    var audioPlayer:AVAudioPlayer?

    func playSound(fileName:NSString)
        let path = NSBundle.mainBundle().pathForResource(fileName, ofType:"wav")
        let url = NSURL.fileURLWithPath(path!)

        do {
            try audioPlayer = AVAudioPlayer(contentsOfURL: url)
            audioPlayer?.delegate = self
        } catch {
            print("Player not available")

    //MARK : AVAudioPlayerDelegate
    func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
        print("finished playing, do something else here")