95 lines
2.2 KiB
Swift
95 lines
2.2 KiB
Swift
//
|
|
// WebView.swift
|
|
// AutoCat
|
|
//
|
|
// Created by Selim Mustafaev on 14.04.2025.
|
|
// Copyright © 2025 Selim Mustafaev. All rights reserved.
|
|
//
|
|
|
|
import WebKit
|
|
import SwiftUI
|
|
|
|
class WebViewCoordinator: NSObject, WKNavigationDelegate {
|
|
|
|
var decidePolicyClosure: ((WKNavigationAction) async -> WKNavigationActionPolicy)?
|
|
|
|
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction) async -> WKNavigationActionPolicy {
|
|
if let decidePolicyClosure {
|
|
return await decidePolicyClosure(navigationAction)
|
|
} else {
|
|
return .allow
|
|
}
|
|
}
|
|
}
|
|
|
|
#if os(macOS)
|
|
|
|
struct WebView: NSViewRepresentable {
|
|
|
|
let url: URL
|
|
let userAgent: String?
|
|
|
|
@State private var delegate = WebViewCoordinator()
|
|
|
|
func makeNSView(context: Context) -> WKWebView {
|
|
|
|
let webView = WKWebView()
|
|
webView.navigationDelegate = context.coordinator
|
|
return webView
|
|
}
|
|
|
|
func updateNSView(_ webView: WKWebView, context: Context) {
|
|
|
|
webView.customUserAgent = userAgent
|
|
webView.navigationDelegate = context.coordinator
|
|
|
|
let request = URLRequest(url: url)
|
|
webView.load(request)
|
|
}
|
|
|
|
func makeCoordinator() -> WebViewCoordinator {
|
|
|
|
delegate
|
|
}
|
|
}
|
|
|
|
#else
|
|
struct WebView: UIViewRepresentable {
|
|
|
|
let url: URL
|
|
let userAgent: String?
|
|
|
|
@State private var delegate = WebViewCoordinator()
|
|
|
|
func makeUIView(context: Context) -> WKWebView {
|
|
|
|
let webView = WKWebView()
|
|
webView.navigationDelegate = context.coordinator
|
|
return webView
|
|
}
|
|
|
|
func updateUIView(_ webView: WKWebView, context: Context) {
|
|
|
|
webView.customUserAgent = userAgent
|
|
webView.navigationDelegate = context.coordinator
|
|
|
|
let request = URLRequest(url: url)
|
|
webView.load(request)
|
|
}
|
|
|
|
func makeCoordinator() -> WebViewCoordinator {
|
|
|
|
delegate
|
|
}
|
|
}
|
|
#endif
|
|
|
|
extension WebView {
|
|
|
|
func decidePolicy(closure: @escaping (WKNavigationAction) async -> WKNavigationActionPolicy) -> Self {
|
|
|
|
delegate.decidePolicyClosure = closure
|
|
return self
|
|
}
|
|
}
|