[英]Increment Recorded Audio File Name
Xcode 7.3.1, Swift 2 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: repeat
循环将执行以下操作:
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. 您可以使用
NSDefault
保持运行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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.