[英]Swift - Sort table view cells by creation date
在我的應用程序中,用戶可以錄制音頻(如Voice Memos )。 完成記錄后,需要用戶輸入輸入信息才能為記錄命名,並且音頻將顯示在UITableView
。 錄制的音頻按其名稱排序(按字母順序)。 我需要按創建日期對它們進行排序-最后創建的音頻將首先出現。 我用了兩個數組-
1.recordedAudioFilesURLArray(類型:URL)和2.recordedAudioFileName(類型:String)。
錄制的音頻將保存在文檔目錄中。 這是我的代碼示例...
func getRecordedAudioFilesFromDocDirectory() {
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
let directoryContents = try FileManager.default.contentsOfDirectory( at: documentsUrl, includingPropertiesForKeys: nil, options: [])
recordedAudioFilesURLArray = directoryContents.filter{ $0.pathExtension == "m4a" }
} catch let error as NSError {
print(error.localizedDescription)
}
recordedAudioFileNames = recordedAudioFilesURLArray.flatMap({$0.deletingPathExtension().lastPathComponent})
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recordedAudioFilesURLArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = recordedAudioFileNames[indexPath.row] as! NSString as String
return cell
}
這個stackoverflow答案顯示了如何使用NSFileManager API獲取文件創建日期。
使用以上答案,我嘗試了一個示例。
//This array will hold info like filename and creation date. You can choose to create model class for this
var fileArray = [[String:NSObject]]()
//traverse each file in the array
for path in recordedAudioFilesURLArray!
{
//get metadata (attibutes) for each file
let dictionary = try? NSFileManager.defaultManager().attributesOfItemAtPath(path.path!)
//save creationDate for each file, we will need this to sort it
let fileDictionary = ["fileName":path.lastPathComponent!, NSFileCreationDate:dictionary?[NSFileCreationDate] as! NSDate]
fileArray.append(fileDictionary)
}
//sorting goes here
fileArray.sortInPlace { (obj1, obj2) -> Bool in
let date1 = obj1[NSFileCreationDate] as! NSDate
let date2 = obj2[NSFileCreationDate] as! NSDate
return (date2.compare(date1) == .OrderedDescending)
}
//Let's check the result
for dictionary in fileArray
{
NSLog("\(dictionary["fileName"])")
}
它為我工作。 希望能有所幫助。
注意 :這只是我嘗試的示例。 您可能需要進行一些修改才能適合您的情況。
嘗試使用以下代碼func getRecordedAudioFilesFromDocDirectory(){var temprecordedAudioFilesArray:[NSDictionary] = []
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
let directoryContents = try FileManager.default.contentsOfDirectory( at: documentsUrl, includingPropertiesForKeys: nil, options: [])
recordedAudioFilesURLArray = directoryContents.filter{ $0.pathExtension == "mp3" }
} catch let error as NSError {
print(error.localizedDescription)
}
for item in recordedAudioFilesURLArray {
var fileName: String?
var creationDate : Date?
let path: String = item.path
do{
let attr = try FileManager.default.attributesOfItem(atPath: path)
creationDate = attr[FileAttributeKey.creationDate] as? Date
fileName = item.lastPathComponent
let fileInfo = ["filepath": item, "name": fileName!, "createnDate": creationDate!]
temprecordedAudioFilesArray.append(fileInfo as NSDictionary)
}
catch {
}
}
temprecordedAudioFilesArray.sort(by: { (($0 as! Dictionary<String, AnyObject>)["createnDate"] as? NSDate)?.compare(($1 as! Dictionary<String, AnyObject>)["createnDate"] as? NSDate as! Date) == .orderedAscending})
for file in temprecordedAudioFilesArray{
recordedAudioFileNames.append((file["name"] as? String)!)
print(file["name"])
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.