Skip to content

Instantly share code, notes, and snippets.

@michzio
Created March 16, 2022 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michzio/a1d271677b78c1e2696e2b23f144d25c to your computer and use it in GitHub Desktop.
Save michzio/a1d271677b78c1e2696e2b23f144d25c to your computer and use it in GitHub Desktop.
DocumentPreview wrapping UIDocumentInteractionController
struct DocumentPreview: UIViewControllerRepresentable {
final class Coordintor: NSObject, UIDocumentInteractionControllerDelegate {
private let parent: DocumentPreview
init(_ parent: DocumentPreview) {
self.parent = parent
}
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
parent.viewController
}
func documentInteractionControllerDidEndPreview(_ controller: UIDocumentInteractionController) {
controller.delegate = nil
parent.isActive.wrappedValue = false
}
public final func documentInteractionControllerDidDismissOpenInMenu(_ controller: UIDocumentInteractionController) {
controller.delegate = nil
parent.isActive.wrappedValue = false
}
public final func documentInteractionController(
_ controller: UIDocumentInteractionController,
didEndSendingToApplication _: String?
) {
controller.delegate = nil
parent.isActive.wrappedValue = false
}
}
private static var documentInteractionController: UIDocumentInteractionController?
private let viewController = UIViewController()
private let isActive: Binding<Bool>
init(isActive: Binding<Bool>, url: URL) {
self.isActive = isActive
Self.documentInteractionController = UIDocumentInteractionController(url: url)
}
func makeUIViewController(context: UIViewControllerRepresentableContext<DocumentPreview>) -> UIViewController {
viewController
}
func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<DocumentPreview>) {
guard isActive.wrappedValue && Self.documentInteractionController?.delegate == nil else { return }
Self.documentInteractionController?.delegate = context.coordinator
Self.documentInteractionController?.presentOptionsMenu(from: viewController.view.bounds, in: viewController.view, animated: true)
}
func makeCoordinator() -> Coordintor {
Coordintor(self)
}
}
extension View {
func documentPreview(isActive: Binding<Bool>, url: URL) -> some View {
background(DocumentPreview(isActive: isActive, url: url))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment