NSFileManager+Haneke.swift 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. //
  2. // NSFileManager+Haneke.swift
  3. // Haneke
  4. //
  5. // Created by Hermes Pique on 8/26/14.
  6. // Copyright (c) 2014 Haneke. All rights reserved.
  7. //
  8. import Foundation
  9. extension FileManager {
  10. func enumerateContentsOfDirectory(atPath path: String, orderedByProperty property: String, ascending: Bool, usingBlock block: (URL, Int, inout Bool) -> Void ) {
  11. let directoryURL = URL(fileURLWithPath: path)
  12. do {
  13. let contents = try self.contentsOfDirectory(at: directoryURL, includingPropertiesForKeys: [URLResourceKey(rawValue: property)], options: FileManager.DirectoryEnumerationOptions())
  14. let sortedContents = contents.sorted(by: {(URL1: URL, URL2: URL) -> Bool in
  15. // Maybe there's a better way to do this. See: http://stackoverflow.com/questions/25502914/comparing-anyobject-in-swift
  16. var value1 : AnyObject?
  17. do {
  18. try (URL1 as NSURL).getResourceValue(&value1, forKey: URLResourceKey(rawValue: property))
  19. } catch {
  20. return true
  21. }
  22. var value2 : AnyObject?
  23. do {
  24. try (URL2 as NSURL).getResourceValue(&value2, forKey: URLResourceKey(rawValue: property))
  25. } catch {
  26. return false
  27. }
  28. if let string1 = value1 as? String, let string2 = value2 as? String {
  29. return ascending ? string1 < string2 : string2 < string1
  30. }
  31. if let date1 = value1 as? Date, let date2 = value2 as? Date {
  32. return ascending ? date1 < date2 : date2 < date1
  33. }
  34. if let number1 = value1 as? NSNumber, let number2 = value2 as? NSNumber {
  35. return ascending ? number1 < number2 : number2 < number1
  36. }
  37. return false
  38. })
  39. for (i, v) in sortedContents.enumerated() {
  40. var stop : Bool = false
  41. block(v, i, &stop)
  42. if stop { break }
  43. }
  44. } catch {
  45. Log.error(message: "Failed to list directory", error: error)
  46. }
  47. }
  48. }
  49. func < (lhs: NSNumber, rhs: NSNumber) -> Bool {
  50. return lhs.compare(rhs) == ComparisonResult.orderedAscending
  51. }