0

In my app user can record audio (Like Voice Memos). After finishing record, it takes input from the user to give the record a name and audios are shown in UITableView. Recorded audios are sorted by their name (Alphabetically). I need to sort them by creation date - last created audio will be appeared first. I used two arrays -

1.recordedAudioFilesURLArray (Type: URL) & 2.recordedAudioFileName (Type: String).

Recorded audios are saved in document directory. Here is my code sample...

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
}
Just a coder
  • 15,480
  • 16
  • 85
  • 138
pigeon_39
  • 1,503
  • 2
  • 22
  • 34

2 Answers2

0

This stackoverflow answer shows how can we get file creation date using NSFileManager API.

Using the above answer, I have tried a sample.

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

It's working for me. Hope that helps.

Note: This is just a sample I tried. You may need some modification to work for your case.

Community
  • 1
  • 1
Anoop Nyati
  • 339
  • 2
  • 11
0

Try following code 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"])
    }

}
Akhil Shrivastav
  • 427
  • 3
  • 13
  • the elements in **temprecordedAudioFilesArray** are sorted perfectly. But according to this I need to sort **recordedAudioFilesURLArray** because this array contains URL of recorded sounds whick are needed to play them. How to do so ?? Can you help ? – pigeon_39 Jan 11 '17 at 10:24
  • declare `temprecordedAudioFilesArray` outside function(where u declared recordedAudioFilesURLArray) and add one more key in file info dictionary `let fileInfo = ["filepath": item, "name": fileName!, "createnDate": creationDate!] as [String : Any]` and when u want to play refer `temprecordedAudioFilesArray` instead of `recordedAudioFilesURLArray `Hope this helps – Akhil Shrivastav Jan 11 '17 at 10:28
  • also make `recordedAudioFilesURLArray` as local variable and use `temprecordedAudioFilesArray ` in place of it. you need code changes for this as `temprecordedAudioFilesArray ` is array of `URL` but `temprecordedAudioFilesArray ` is array of dictionary. – Akhil Shrivastav Jan 11 '17 at 10:52
  • sorry...it seems complex to me....can you just add an extra field for URL in your dictionary and edit your code please... By the way thank you very much for your co-operation. – pigeon_39 Jan 11 '17 at 11:00
  • edited the code and to access url u can use `print(temprecordedAudioFilesArray[indexPath.row]["filepath"])` – Akhil Shrivastav Jan 11 '17 at 11:14