我想使用 SFSafariViewController 打开桌面版本的链接。我已经找到了如何使用 SFSafariViewController 的解决方案,并分别找到了如何打开桌面版本链接的解决方案,但我无法让这两者一起工作。我想显示带有浏览器页眉和页脚的应用内默认浏览器,但我必须使用桌面版本的链接。就像我说的,我已经成功地让它们单独工作,但不能一起工作。我附加的版本是我使用链接的桌面版本的版本,但如果需要,我可以附加使 SFSafariViewController 工作的版本。
URL 按钮和“Safari”视图
struct URLButton<Content: View>: View {
var content: Content
var url: String
@AppStorage("LinkDestination") var linkDestination = 0
@State var showSafariView = false
var safariURL: URL {
return URL(string: url)!
}
@ViewBuilder var body: some View {
switch linkDestination {
case 0:
Button(action: {
showSafariView = true
}) {
content.fullScreenCover(isPresented: $showSafariView) {
SafariView(url: URL(string: url)!).edgesIgnoringSafeArea(.all)
}
}
case 1:
Link(destination: safariURL) {
content
}
default:
content
}
}
}
struct SafariView: UIViewControllerRepresentable {
var url: URL
func makeUIViewController(context: Context) -> UIViewController {
let webView = WKWebView()
webView.customUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36"
webView.load(URLRequest(url: url))
let viewController = UIViewController()
viewController.view = webView
return viewController
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
}
}
查看
struct ImportView: View {
let urlString = "https://www.google.com"
var body: some View {
URLButton(content: ExportButton(), url: urlString)
}
}
要实现您所描述的功能,即您想要使用 SFSafariViewController 显示桌面版本的链接,同时维护应用内浏览器页眉和页脚,您需要对代码进行一些调整。
这是使用 SFSafariViewController 的 SafariView 结构的更新版本:
迅速
import SwiftUI
import SafariServices
struct SafariView: UIViewControllerRepresentable {
var url: URL
func makeUIViewController(context: Context) -> UIViewController {
let safariViewController = SFSafariViewController(url: url)
safariViewController.preferredControlTintColor = UIColor.systemBlue // Change the color of toolbar items
// Customize Safari view controller properties here if needed
return safariViewController
}
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
// Update the Safari view controller if needed
}
}
然后在您的 URLButton 视图中,您可以使用此 SafariView 显示桌面版本的链接:
struct URLButton<Content: View>: View {
var content: Content
var url: String
@AppStorage("LinkDestination") var linkDestination = 0
@State private var showSafariView = false
var safariURL: URL {
return URL(string: url)!
}
@ViewBuilder var body: some View {
switch linkDestination {
case 0:
Button(action: {
showSafariView = true
}) {
content
}
.fullScreenCover(isPresented: $showSafariView) {
SafariView(url: URL(string: url)!)
}
case 1:
Link(destination: safariURL) {
content
}
default:
content
}
}
}