iosswiftiphone-8

FileManager.default.contentsOfDirectory return array with different sorting in iphone 8


I am trying to get contents of directory by using following method.

let files: [String]? = try? FileManager.default.contentsOfDirectory(atPath: self.targetDirectory)

It was working perfectly in all devices but in case of IPhone 8, i get results in different sorting.

For example, in case of iPhone 7+, i get following results.

Printing description of filterFiles:
▿ Optional<Array<String>>
  ▿ some : 2 elements
    - 0 : "0.m4a"
    - 1 : "1.m4a"

But in case of iPhone 8, i get following results:

Printing description of files:
▿ Optional<Array<String>>
  ▿ some : 2 elements
    - 0 : "1.m4a"
    - 1 : "0.m4a"

In both cases, results are same but sorting is different. Can anyone help me about that.

Thanks in advance.


Solution

  • NSFileManager doesn't sort the list of files. But you can do it yourself using sorted method of array. The code will look like this:

    let files: [String]? = try? FileManager.default.contentsOfDirectory(atPath: self.targetDirectory)
    let sortedFiles = files?.sorted()