Creation of an AVAudioRecorder object is used to record audio. These class has a method to stop recording and release resources.

In addition to unnecessary resources (such as memory and instances of codecs) being held, failure to properly stop and release these object if it is no longer needed may also lead to continuous battery consumption for mobile devices.

Non compliant Code Example

import AVFoundation

var audioRecorder: AVAudioRecorder?

func startRecording() {
    let settings = [
        AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
        AVSampleRateKey: 12000,
        AVNumberOfChannelsKey: 1,
        AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
    ]

    do {
        audioRecorder = try AVAudioRecorder(url: getDocumentsDirectory().appendingPathComponent("recording.m4a"), settings: settings)
        audioRecorder?.record()
    } catch {
        // Handle error
    }
}

Compliant Solution

import AVFoundation

var audioRecorder: AVAudioRecorder?

func startRecording() {
    let settings = [
        AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
        AVSampleRateKey: 12000,
        AVNumberOfChannelsKey: 1,
        AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
    ]

    do {
        audioRecorder = try AVAudioRecorder(url: getDocumentsDirectory().appendingPathComponent("recording.m4a"), settings: settings)
        audioRecorder?.record()
    } catch {
        // Handle error
    }
}

func stopRecording() {
    if let recorder = audioRecorder, recorder.isRecording {
        recorder.stop()
        audioRecorder = nil
    }
}