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")
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!)
You can use NSDefault
to keep running id. It stored permanently in your app even though the apps is terminated.
For example here, I use a class with static function:
class FileUtil {
let key = "runningId"
static func getRunningID() {
let prefs = NSUserDefaults.standardUserDefaults()
// set initial value if first time
if var runningid = prefs.valueForKey(key) as? Int{
print("current id: \(runningid)")
// increase by 1 and return
runningid += 1
// dont forget to save back after increment
prefs.setInteger(runningid, forKey: key)
return runningid;
}else{
// not set yet, then set the init value
prefs.setInteger(1, forKey: key)
}
}
}
So in your controller could simply call
let audioFileURL = directoryURL.URLByAppendingPathComponent("PWAC_" + FileUtil. getRunningID() + ".m4a")
Each your Audio file has a unique name with date string everytime.
let date = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateFormatter.dateFormat = "yyyy-MM-ddHHmmssSSS"
let string = dateFormatter.stringFromDate(date)
audioFileURL = directoryURL.URLByAppendingPathComponent("PWAC_\(string).m4a")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.