domingo, 25 de octubre de 2015

How to pass data from a viewController to another one

1. In the viewController RecordSoundsViewController we record an audio. This audio is represented by the class RecordedAudio. So in RecordSoundsViewController we have a variable recordedAudio of type RecordedAudio, that we want to pass to another viewController called PlaySoundsViewController that will play the audio.

1.1. class RecordedAudio

class RecordedAudio: NSObject{
    var filePathURL: NSURL!
    var title:String!

}

1.2. class RecordSoundsViewController

class RecordSoundsViewController: UIViewController, AVAudioRecorderDelegate {
    var recordedAudio:RecordedAudio!
}

1.3 class PlaySoundsViewController

class PlaySoundsViewController: UIViewController {
    var receivedAudio:RecordedAudio!
}

2. We will pass the data from RecordSoundsViewController to PlaySoundsViewController overriding the function prepareForSegue from UIViewController. The function prepareForSegue is called just before a segue is about to be performed. Inside the function we will controller that the segue is the one that we want because the scene could have multiple segues. The constant playSoundVC will be the destination view controller of the segue. The keyword "as!" convert the destinationViewController to the desired type PlaySoundsViewController. We get the data from the sender of the segue. We will pass the data to the recordedAudio in PlaySoundsViewController.


class RecordSoundsViewController: UIViewController, AVAudioRecorderDelegate {

    var recordedAudio:RecordedAudio!
        
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if(segue.identifier == "stopRecording") {
            let playSoundVC:PlaySoundsViewController = segue.destinationViewController as! PlaySoundsViewController
            let data = sender as! RecordedAudio
            playSoundVC.receivedAudio = data
        }
    }
}

No hay comentarios:

Publicar un comentario