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