Created
January 7, 2024 19:41
-
-
Save dskuza/09bb4707dccdbaf43d7a27b0bb7fbe4c to your computer and use it in GitHub Desktop.
SFSafariViewController in SwiftUI
This file contains hidden or 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
import SafariServices | |
import SwiftUI | |
import UIKit | |
/// A SwiftUI view that wraps SFSafariViewController | |
struct SafariView: UIViewControllerRepresentable { | |
private let url: URL | |
init(url: URL) { | |
self.url = url | |
} | |
func makeUIViewController(context: Context) -> SFSafariViewController { | |
return SFSafariViewController(url: url) | |
} | |
func updateUIViewController(_ uiViewController: SFSafariViewController, context: Context) { | |
} | |
} | |
/// A SwiftUI view that utilizes SafariView and presents it | |
/// as a fullscreen cover. This implementation uses a tap | |
/// gesture recognizer as the entry point. | |
struct SafariLink<Content: View>: View { | |
@State var isPresented = false | |
private let url: URL? | |
private var content: () -> Content | |
init(url: URL?, content: @escaping () -> Content) { | |
self.url = url | |
self.content = content | |
} | |
var body: some View { | |
if let url = url { | |
content() | |
.onTapGesture { | |
isPresented = true | |
} | |
.fullScreenCover(isPresented: $isPresented) { | |
SafariView(url: url) | |
.ignoresSafeArea() | |
} | |
} else { | |
content() | |
} | |
} | |
} | |
/// Defines a view that uses SafariLink to open mozilla.org | |
/// when tapping on its Text content | |
struct MyView: View { | |
var body: some View { | |
SafariLink(url: URL(string: "https://mozilla.org")) { | |
Text("Tap to open mozilla.org") | |
} | |
} | |
} | |
// Test it out! | |
import PlaygroundSupport | |
let view = MyView().frame(width: 393, height: 852) | |
PlaygroundPage.current.setLiveView(view) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment