Alistair Cooper Alistair Cooper - 1 month ago 12
Swift Question

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)

Answer

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.

Comments