Bill Bill - 4 months ago 36
iOS Question

Increment Recorded Audio File Name

Xcode 7.3.1, Swift 2

I have the following line of code in my view controller that sets the file name of my recorded audio. Although each file has a unique name, I would really like it to be shorter, but unique. I would like to increment the file name by one if it already exists.

I am not sure the proper terminology to properly look this up, so I am hoping one of you could point me in the right direction.

// Set the default audio file
let audioFileURL = directoryURL.URLByAppendingPathComponent("PWAC_" + NSUUID().UUIDString + ".m4a")

Answer

A repeat loop will do:

var index = 0
var audioFileURL: NSURL!

repeat {
    index += 1
    audioFileURL = directoryURL.URLByAppendingPathComponent("PWAC_\(index).m4a")
} while NSFileManager.defaultManager().fileExistsAtPath(audioFileURL.path!)