Created
March 16, 2022 13:31
-
-
Save michzio/a1d271677b78c1e2696e2b23f144d25c to your computer and use it in GitHub Desktop.
DocumentPreview wrapping UIDocumentInteractionController
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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