0

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/
9
  • Well, how would you go about accessing /Users/me/Desktop/A/Singe/File.txt? Commented Mar 26, 2018 at 20:12
  • let url = URL(fileURLWithPath: "/Users/me/Desktop/A/Single/File.txt") Commented Mar 26, 2018 at 20:14
  • Good. Now, how given an n: Int = 123, how would you go about accessing /Users/me/Desktop/A/Single/File123.txt, using n? Commented Mar 26, 2018 at 20:15
  • That's what my question about! Commented Mar 26, 2018 at 20:16
  • I mean for the specific case of n = 123. How can you put the int 123 in that path, so that you can initialize a URL from it? Commented Mar 26, 2018 at 20:24

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

11 Comments

Thank you very much, @vadian. But how can I use .reversed() method using FileManager?
The result is an array. You can use any function array responds to, amongst others .reverse
Where to put it? This is unfamiliar syntax for me.
At the end of the FileManager line ...options: [.skipsHiddenFiles]).reversed()
Damn! Thanks a lot! ))
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.