Alistair Cooper
Alistair Cooper

Reputation: 291

Are audio files in DocumentDirectory deleted when Core Data entity is deleted?

I'm recording audio with AVFoundation and saving the file in the DocumentDirectory. Then in Core Data the "sounds" entity stores the url as a string. Everything's working great. However I'm wondering: when sounds entities are deleted from Core Data how do to you delete the file from the DocumentDirectory ...or does that automagically happen?

My code to save to disk:

    let directoryURL = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).first

    let audioFileName = NSUUID().UUIDString + ".m4a"
    let audioFileURL = directoryURL!.URLByAppendingPathComponent(audioFileName)

    // URL for Core Data store
    audioURL = audioFileName

    // Setup audio session

    let audioSession = AVAudioSession.sharedInstance()
    do {
        try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: AVAudioSessionCategoryOptions.DefaultToSpeaker)
    } catch _ {
        print("Error creating AVAudioSession")
    }

    let recordSettings = [AVFormatIDKey: NSNumber(unsignedInt: kAudioFormatMPEG4AAC), AVSampleRateKey: 44100.0, AVNumberOfChannelsKey: 2]

    // Initiate and prepare recorder

    audioRecorder = try?AVAudioRecorder(URL: audioFileURL!, settings: recordSettings)
    audioRecorder?.delegate = self
    audioRecorder?.meteringEnabled = true
    audioRecorder?.prepareToRecord()

Thank you very much for any assistance! Sorry, I'm finding it a little difficult to track files in the document directory in the sim. (I'm in Swift 2.3)

Upvotes: 0

Views: 108

Answers (1)

Tom Harrington
Tom Harrington

Reputation: 70946

Deleting a Core Data instance will affect-- at most-- things in the Core Data store. Core Data doesn't know that the string you saved points to a file, so it doesn't try to do anything special with the string.

You can remove the file using the removeItemAtURL:error: method on NSFileManager. A good place to do this would be in your managed object subclass-- override prepareForDeletion and delete the file there.

Upvotes: 0

Related Questions