/// Asyncronously copies images from exampleImages.bundle to the documents directory and reveals them in the document browser. private func prepareExampleImages() { DispatchQueue.global(qos: .userInitiated).async { guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { fatalError("Can't get URL for FileManager.SearchPathDirectory.documentDirectory") } guard let exampleImageBundlePath = Bundle.main.path(forResource: "exampleImages", ofType: "bundle") else { fatalError("Example image bundle missing or unreadable.") } let fileManager = FileManager.default guard let filenames = try? fileManager.contentsOfDirectory(atPath: exampleImageBundlePath), filenames.count == 3 else { fatalError("Expected three example images in exampleImages.bundle") } var destinationURLs = [URL]() for filename in filenames { let imageURL = URL(fileURLWithPath: "\(exampleImageBundlePath)/\(filename)") let destinationURL = documentsDirectory.appendingPathComponent(filename) destinationURLs.append(destinationURL) do { try fileManager.copyItem(at: imageURL, to: destinationURL) } catch { // file exists error: running tutorial with files of this name already present // that's ok, we don't want to overwrite user data, skip this file // In some locales, the error.localizedDescription fails to load, so the error code is returned instead. if error.localizedDescription.contains("exist") || error.localizedDescription.contains("ERR516") { // skip this file continue } else { // unknown errors are not handled; skip file // TODO unified error handling show the user a message about example image not loading assertionFailure("Unknown error while copying image from example bundle to documents directory!") continue } } } self.exampleImageURLs = destinationURLs // tell document controller to reveal the example images, which updates last used date // means if we do it in reverse order they will show up in the correct order in Recents tab (most recently revealed first) destinationURLs = destinationURLs.reversed() // delay to make sure the calls arrive at the remote view controller in this specific order var delay = 0.0 for url in destinationURLs { DispatchQueue.main.asyncAfter(deadline: .now() + delay) { self.presenterVC.documentBrowserVC.revealDocument(at: url, importIfNeeded: true) { (url, error) in // unknown error TODO universal user-facing error handling assert(error == nil, "UIDocumentBrowserViewController can't reveal the image! \(error!.localizedDescription)") } } delay += 0.2 } } }