domingo, 25 de octubre de 2015

How to implement a delegate

1. We have the class RecordSoundsViewController of type UIViewController. We want that this class implements a function included inside the class AVAudioRecorderDelegate called audioRecorderDidFinishRecording. The initial class is


class RecordSoundsViewController: UIViewController {
   var audioRecorder:AVAudioRecorder!

   @IBAction func recordAudio(sender: UIButton) {
        ...
        try! audioRecorder = AVAudioRecorder(URL: filePath!, settings: [:])
        ...
    }
}

2. We add the type AVAudioRecorderDelegate to this class


class RecordSoundsViewController: UIViewController, AVAudioRecorderDelegate {
   var audioRecorder:AVAudioRecorder!

   @IBAction func recordAudio(sender: UIButton) {
        ...
        tryaudioRecorder = AVAudioRecorder(URL: filePath!, settings: [:])
        ...
    }
}

3. After initialize the audioRecorder instance we declare that the class RecordSoundsViewController will be the delegate for audioRecorder

class RecordSoundsViewController: UIViewControllerAVAudioRecorderDelegate {
   var audioRecorder:AVAudioRecorder!

   @IBAction func recordAudio(sender: UIButton) {
        ...
        tryaudioRecorder = AVAudioRecorder(URL: filePath!, settings: [:])
        audioRecorder.delegate = self
        ...
    }
}

4. We add a function audioRecorderDidFinishRecording in the class RecordSoundsViewController

class RecordSoundsViewController: UIViewControllerAVAudioRecorderDelegate {
   var audioRecorder:AVAudioRecorder!

   @IBAction func recordAudio(sender: UIButton) {
        ...
        tryaudioRecorder = AVAudioRecorder(URL: filePath!, settings: [:])
        audioRecorder.delegate = self
        ...
    }

    func audioRecorderDidFinishRecording(recorder: AVAudioRecorder, successfully flag: Bool) {
        <#code#>
    }
}

Concepts:
- Class AVAudioRecorder has a variable called delegate of type AVAudioRecorderDelegate
class AVAudioRecorder{
   var delegate: AVAudioRecorderDelegate!
}

AVAudioRecorderDelegate is a list of methods, one of them audioRecorderDidFinishRecording
protocol AVAudioRecorderDelegate {
   func audioRecorderDidFinishRecording()
}

- In the RecordSoundsViewController of type AVAudioRecorderDelegate, when we see 
audioRecorder.delegate = self
we say that RecordSoundsViewController is becoming AVAudioRecorder.delegate so RecordSoundsViewController can implement the functions inside AVAudioRecorderDelegate like audioRecorderDidFinishRecording


No hay comentarios:

Publicar un comentario