Swift - 按创建日期对表格视图单元格进行排序

时间:2017-01-11 06:40:18

标签: ios swift uitableview sorting

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

1.recordedAudioFilesURLArray(Type:URL)& 2.recordedAudioFileName(Type: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
}

2 个答案:

答案 0 :(得分:0)

这个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"])")
    }

它为我工作。希望有所帮助。

  

注意:这只是我试过的一个示例。您可能需要进行一些修改   为你的案子工作。

答案 1 :(得分:0)

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

}