Andy Jazz
Andy Jazz

Reputation: 58093

Reading in array of elements from macOS directory

I can read in elements (images or videos) uploaded in Xcode's project this way:

let photos = (1...9).map {
    NSImage(named: NSImage.Name(rawValue: "000\($0)"))
}

or like this:

let videos = (1...100).map { _ in
    Bundle.main.urls(forResourcesWithExtension: "mov", subdirectory: nil)![Int(arc4random_uniform(UInt32(100)))]
}

But how to read in files (as array) from macOS directory using .map method?

/Users/me/Desktop/ArrayOfElements/

Upvotes: 0

Views: 130

Answers (1)

vadian
vadian

Reputation: 285064

First of all your second way is very expensive, the array of movie URLs is read a hundred times from the bundle. This is more efficient:

let resources = Bundle.main.urls(forResourcesWithExtension: "mov", subdirectory: nil)!
let videos = (1...100).map { _ in
    resources[Int(arc4random_uniform(100))]
}

Reading from /Users/me/Desktop is only possible if the application is not sandboxed, otherwise you can only read form the application container.

To get all files (as [URL]) from a directory use FileManager:

let url = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Desktop/ArrayOfElements")
do {
    let fileURLs = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
    let movieURLs = fileURLs.filter{ $0.pathExtension == "mov" }
    print(movieURLs)
} catch { print(error) }

Rather than using map I recommend to implement an Array extension adding shuffle()

Upvotes: 1

Related Questions