-1
Xcode 7.3.1,Swift 2.2重命名文件而不輸入文件擴展名
我下面的代碼是按預期重命名文件。我的問題是,我想要在警報文本輸入字段中輸入沒有擴展名的「新文件名」。然後,一旦用戶按下「是」,文件擴展名「m4u」被添加到新名稱並最終重命名文件「新文件名.m4u」。我不希望用戶必須處理文件擴展名。
任何援助將不勝感激.....
func askToRename(row:Int) {
let recording = self.arrayRecordings[row]
let recordingURL = self.arrayRecordingsURL[row]
let alert = UIAlertController(title: "Rename",
message: "Rename Recording \(recording)?",
preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Yes", style: .Default, handler: {[unowned alert] action in
print("yes was tapped \(self.arrayRecordingsURL[row])")
if let textFields = alert.textFields{
let tfa = textFields as [UITextField]
let text = tfa[0].text
let url = NSURL(fileURLWithPath: text!)
self.renameRecording(recordingURL, to: url)
}
}))
alert.addAction(UIAlertAction(title: "No", style: .Default, handler: {action in
print("no was tapped")
}))
alert.addTextFieldWithConfigurationHandler({textfield in
textfield.placeholder = "Enter a filename"
textfield.text = "\(recordingURL.lastPathComponent!)"
})
self.presentViewController(alert, animated:true, completion:nil)
}
func renameRecording(from:NSURL, to:NSURL) {
let documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let toURL = documentsDirectory.URLByAppendingPathComponent(to.lastPathComponent!)
print("renaming file \(from.absoluteString) to \(to) url \(toURL)")
let fileManager = NSFileManager.defaultManager()
fileManager.delegate = self
do {
try NSFileManager.defaultManager().moveItemAtURL(from, toURL: toURL)
} catch let error as NSError {
print(error.localizedDescription)
} catch {
print("error renaming recording")
}
dispatch_async(dispatch_get_main_queue(), {
self.listRecordings()
// self.tableView.reloadData()
})
}
func listRecordings() {
let documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
do {
let urls = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsDirectory, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles)
self.arrayRecordingsURL = urls.filter({ (name: NSURL) -> Bool in
return name.lastPathComponent!.hasSuffix("m4a")
})
} catch let error as NSError {
print(error.localizedDescription)
} catch {
print("something went wrong listing recordings")
}
}
extension ViewControllerFileManager: NSFileManagerDelegate {
func fileManager(fileManager: NSFileManager, shouldMoveItemAtURL srcURL: NSURL, toURL dstURL: NSURL) -> Bool {
print("should move \(srcURL) to \(dstURL)")
return true
}
}
如何添加在你的代碼路徑擴展。 // let text = tfa [0] .text +「.m4u」 – WeiJay
感謝Wei Jay的幫助,不幸的是沒有做到這一點。 – Bill