Post

Replies

Boosts

Views

Activity

Reply to Disabling pop-up presentations in a WKWebView in an immersive app
Relevant code: import SwiftUI import WebKit struct WebView: UIViewRepresentable { typealias UIViewType = WKWebView let webView: WKWebView func makeUIView(context: Context) -> WKWebView { return webView } func updateUIView(_ uiView: WKWebView, context: Context) { } } import SwiftUI import WebKit class WebViewModel: ObservableObject { let webView: WKWebView let url: URL @Published var canGoBack: Bool = false @Published var canGoForward: Bool = false @Published var urlString: String = "" init() { let config = WKWebViewConfiguration() webView = WKWebView(frame: .zero, configuration: config) url = URL(string: "https://www.google.com")! setupBindings() loadURL() } private func setupBindings() { webView.publisher(for: \.canGoBack) .assign(to: &$canGoBack) webView.publisher(for: \.canGoForward) .assign(to: &$canGoForward) } func loadURL() { let urlElements = urlString.split(separator: ".") print(urlElements.count) if (urlElements.count > 1 && !urlString.contains(" ")) { f (!urlString.lowercased().contains("https://")) { urlString = String("https://").appending(urlString) } } else { urlString = "https://www.google.com/search?q=" + urlString.replacingOccurrences(of: " ", with: "+") } guard let url = URL(string: urlString) else { return } webView.load(URLRequest(url: url)) } func goForward() { webView.goForward() } func goBack() { webView.goBack() } } import SwiftUI struct BrowserView: View { @StateObject var model: WebViewModel var body: some View { ZStack(alignment: .bottom) { Color.black .ignoresSafeArea() VStack(spacing: 0) { HStack(spacing: 10) { HStack { TextField("Enter an url", text: $model.urlString) .keyboardType(.URL) .textInputAutocapitalization(.none) .padding(10) .onKeyPress(.return) { model.loadURL() return .handled } Spacer() } .background(Color.gray) .presentationCornerRadius(30) Button("Go", action: { model.loadURL() }) .padding(10) } .padding(10) WebView(webView: model.webView) HStack(spacing: 10) { Button(action: { model.goBack() }, label: { Image(systemName: "arrowshape.turn.up.backward") }) .disabled(!model.canGoBack) Button(action: { model.goForward() }, label: { Image(systemName: "arrowshape.turn.up.right") }) .disabled(!model.canGoForward) Spacer() } .padding(10) } } } }
Nov ’24