Ghulam Rasool
Ghulam Rasool

Reputation: 4064

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.

Upvotes: -2

Views: 3881

Answers (2)

SouthernYankee65
SouthernYankee65

Reputation: 1269

To answer the original question, I suggested changing the immutable property files to a mutable property:

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

if files != nil {
    files = files?.sorted()
}

To answer using Swift 5.5:

If you're just looking for a system default sorted file list by file name you can use the following with a URL. There is not a sorted method for atPath: calls in FileManager. Using this method provides a list of URLs to work with. If you need the full path you can use the file[#].path method to get the path to a list item.

let targetDirectoryURL = URL(fileURLWithPath: self.targetDirectory)

do {
    let files = try FileManager.default.contentsOfDirectory(at: targetDirectoryURL), includingPropertiesForKeys: nil, options: .skipsHiddenFiles).sorted { $0.path < $1.path }
} catch {
    print("An error occurred: \(error)")
}

If you want it sorted in reverse order, just change the order inside the closure.

let files = try FileManager.default.contentsOfDirectory(at: targetDirectoryURL, includingPropertiesForKeys: nil, options: .skipsHiddenFiles).sorted { $1.path < $0.path }

Upvotes: 3

Alex
Alex

Reputation: 1245

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()

Upvotes: 4

Related Questions