【问题标题】:Swift - Sort table view cells by creation dateSwift - 按创建日期对表格视图单元格进行排序
【发布时间】:2017-05-25 20:31:37
【问题描述】:

在我的应用中,用户可以录制音频(如 语音备忘录)。录制完成后,需要用户输入给录制文件命名,音频显示在UITableView。录制的音频按其名称(按字母顺序)排序。我需要按创建日期对它们进行排序 - 最后创建的音频将首先出现。我使用了两个数组 -

1.recordedAudioFilesURLArray(类型:URL)& 2.recordedAudioFileName(类型:字符串)。

录制的音频保存在文档目录中。这是我的代码示例...

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
}

【问题讨论】:

  • 你有音频的日期吗?如果是,则共享示例日期数组。
  • 不...兄弟。我没有
  • 如果没有日期,你愿意如何按日期排序?
  • @pigeon_39 其实你可以通过FileManager api获取文件创建日期

标签: ios swift uitableview sorting


【解决方案1】:

stackoverflow answer 展示了我们如何使用 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"])")
    }

它对我有用。希望对您有所帮助。

注意:这只是我尝试的一个示例。您可能需要进行一些修改以 为您的情况工作。

【讨论】:

    【解决方案2】:

    试试下面的代码 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"])
        }
    
    }
    

    【讨论】:

    • temprecordedAudioFilesArray 中的元素已完美排序。但据此,我需要对 recordedAudioFilesURLArray 进行排序,因为该数组包含播放它们所需要的录制声音的 URL。怎么办??你能帮忙吗?
    • 声明temprecordedAudioFilesArray 外部函数(你声明了recordedAudioFilesURLArray)并在文件信息字典let fileInfo = ["filepath": item, "name": fileName!, "createnDate": creationDate!] as [String : Any] 中再添加一个键,当你想播放时参考temprecordedAudioFilesArray 而不是recordedAudioFilesURLArray 希望这有帮助
    • 还将recordedAudioFilesURLArray 设为局部变量并使用temprecordedAudioFilesArray 代替它。您需要为此更改代码,因为 temprecordedAudioFilesArray URL 的数组,但 temprecordedAudioFilesArray 是字典的数组。
    • 对不起...这对我来说似乎很复杂...您可以在字典中添加一个额外的 URL 字段并编辑您的代码...顺便说一句,非常感谢您的合作。
    • 编辑了代码并访问 url 你可以使用print(temprecordedAudioFilesArray[indexPath.row]["filepath"])
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-06
    • 1970-01-01
    相关资源
    最近更新 更多