如何将SFSafariViewController与SwiftUI配合使用?

p8h8hvxi  于 2023-02-11  发布在  Swift
关注(0)|答案(8)|浏览(166)

我试图从NavigationButton呈现SFSafariViewController,但我不确定如何使用SwiftUI来实现。
在UIKit中,我只会:

let vc = SFSafariViewController(url: URL(string: "https://google.com"), entersReaderIfAvailable: true)
    vc.delegate = self

    present(vc, animated: true)
bxpogfeg

bxpogfeg1#

Matteo Pacini post.presentation(Modal())was removed by iOS 13's release的补充。此代码应该可以工作(在Xcode 11.3,iOS 13.0 - 13.3中测试):

import SwiftUI
import SafariServices

struct ContentView: View {
    // whether or not to show the Safari ViewController
    @State var showSafari = false
    // initial URL string
    @State var urlString = "https://duckduckgo.com"

    var body: some View {
        Button(action: {
            // update the URL if you'd like to
            self.urlString = "https://duckduckgo.com"
            // tell the app that we want to show the Safari VC
            self.showSafari = true
        }) {
            Text("Present Safari")
        }
        // summon the Safari sheet
        .sheet(isPresented: $showSafari) {
            SafariView(url:URL(string: self.urlString)!)
        }
    }
}

struct SafariView: UIViewControllerRepresentable {

    let url: URL

    func makeUIViewController(context: UIViewControllerRepresentableContext<SafariView>) -> SFSafariViewController {
        return SFSafariViewController(url: url)
    }

    func updateUIViewController(_ uiViewController: SFSafariViewController, context: UIViewControllerRepresentableContext<SafariView>) {

    }

}
daupos2t

daupos2t2#

SFSafariViewController是一个UIKit组件,因此您需要将其设置为UIViewControllerRepresentable
有关如何将UIKit组件桥接到SwiftUI的更多详细信息,请参见Integrating SwiftUI WWDC 19视频。

struct SafariView: UIViewControllerRepresentable {

    let url: URL

    func makeUIViewController(context: UIViewControllerRepresentableContext<SafariView>) -> SFSafariViewController {
        return SFSafariViewController(url: url)
    }

    func updateUIViewController(_ uiViewController: SFSafariViewController,
                                context: UIViewControllerRepresentableContext<SafariView>) {

    }

}

提醒一下:SFSafariViewController应该显示在另一个视图控制器的顶部,而不是推入导航堆栈。
它还有一个导航栏,这意味着如果你按下视图控制器,你会看到两个导航栏。

它似乎工作-虽然它的小故障-如果提出模态。

struct ContentView : View {

    let url = URL(string: "https://www.google.com")!

    var body: some View {
        EmptyView()
        .presentation(Modal(SafariView(url:url)))
    }
}

它看起来像这样:

我建议通过UIViewRepresentable协议将WKWebView移植到SwiftUI,并使用它来代替。

t8e9dugd

t8e9dugd3#

使用**BetterSafariView**,你可以很容易地在SwiftUI中显示SFSafariViewController。它可以很好地按照苹果的意图工作,而不会失去它最初的推送过渡和滑动解除手势。

用法

.safariView(isPresented: $presentingSafariView) {
    SafariView(url: URL("https://github.com/")!)
}

示例

import SwiftUI
import BetterSafariView

struct ContentView: View {
    
    @State private var presentingSafariView = false
    
    var body: some View {
        Button("Present SafariView") {
            self.presentingSafariView = true
        }
        .safariView(isPresented: $presentingSafariView) {
            SafariView(
                url: URL(string: "https://github.com/stleamist/BetterSafariView")!,
                configuration: SafariView.Configuration(
                    entersReaderIfAvailable: false,
                    barCollapsingEnabled: true
                )
            )
        }
    }
}
os8fio9y

os8fio9y4#

有时候,答案就是不使用SwiftUI!UIKit对SwiftUI的支持非常好,所以我只需要简单地搭建一个到UIKit的桥梁,这样我就可以在SwiftUI的一行中调用SafariController,如下所示:

HSHosting.openSafari(url:URL(string: "https://hobbyistsoftware.com")!)

我只是将应用顶层的UIHostingController替换为HSHostingController
(note- 此类还允许您控制模态的表示样式)

//HSHostingController.swift
import Foundation
import SwiftUI
import SafariServices

class HSHosting {
    static var controller:UIViewController?
    static var nextModalPresentationStyle:UIModalPresentationStyle?

    static func openSafari(url:URL,tint:UIColor? = nil) {
        guard let controller = controller else {
            preconditionFailure("No controller present. Did you remember to use HSHostingController instead of UIHostingController in your SceneDelegate?")
        }

        let vc = SFSafariViewController(url: url)  

        vc.preferredBarTintColor = tint
        //vc.delegate = self

        controller.present(vc, animated: true)
    }
}

class HSHostingController<Content> : UIHostingController<Content> where Content : View {

    override init(rootView: Content) {
        super.init(rootView: rootView)

        HSHosting.controller = self
    }

    @objc required dynamic init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {

        if let nextStyle = HSHosting.nextModalPresentationStyle {
            viewControllerToPresent.modalPresentationStyle = nextStyle
            HSHosting.nextModalPresentationStyle = nil
        }

        super.present(viewControllerToPresent, animated: flag, completion: completion)
    }

}

在场景代理中使用HSHostingController而不是UIHostingController,如下所示:

// Use a HSHostingController as window root view controller.
    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)

        //This is the only change from the standard boilerplate
        window.rootViewController = HSHostingController(rootView: contentView)

        self.window = window
        window.makeKeyAndVisible()
    }

那么当你想打开SFSafariViewController的时候,调用:

HSHosting.openSafari(url:URL(string: "https://hobbyistsoftware.com")!)

例如

Button(action: {
    HSHosting.openSafari(url:URL(string: "https://hobbyistsoftware.com")!)
}) {
    Text("Open Web")
}

更新:请参阅this gist以了解具有附加功能的扩展解决方案

xurqigkl

xurqigkl5#

这里是答案,如果使用WKWebView,但它仍然看起来不正确.

struct SafariView: UIViewRepresentable {

    let url: String

    func makeUIView(context: Context) -> WKWebView {
        return WKWebView(frame: .zero)
    }

    func updateUIView(_ view: WKWebView, context: Context) {
        if let url = URL(string: url) {
            let request = URLRequest(url: url)
            view.load(request)
        }
    }
}
pgpifvop

pgpifvop6#

这在SwiftUI中是可能的,甚至可以保留默认外观,但您需要公开一个UIViewController来使用。首先定义一个SwiftUI UIViewControllerRepresentable,它被传递了一个布尔绑定和一个激活处理程序:

import SwiftUI

struct ViewControllerBridge: UIViewControllerRepresentable {
    @Binding var isActive: Bool
    let action: (UIViewController, Bool) -> Void

    func makeUIViewController(context: Context) -> UIViewController {
        return UIViewController()
    }

    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
        action(uiViewController, isActive)
    }
}

然后,从一个状态属性中给予您计划显示SafariVC的小部件,该状态属性确定是否应该显示该小部件,然后添加此桥以在状态更改时显示VC。

struct MyView: View {
    @State private var isSafariShown = false

    var body: some View {
        Button("Show Safari") {
            self.isSafariShown = true
        }
        .background(
            ViewControllerBridge(isActive: $isSafariShown) { vc, active in
                if active {
                    let safariVC = SFSafariViewController(url: URL(string: "https://google.com")!)
                    vc.present(safariVC, animated: true) {
                        // Set the variable to false when the user dismisses the safari VC
                        self.isSafariShown = false
                    }
                }
            }
            .frame(width: 0, height: 0)
        )
    }
}

请注意,我给予ViewControllerBridge一个宽度和高度为零的固定框架,这意味着您可以将其放在视图层次结构中的任何位置,并且不会对您的UI造成任何重大更改。
--雅各布

jchrr9hc

jchrr9hc7#

以上这些对我来说都不起作用,因为我试图在一个按钮列表中呈现SFSafariViewController。我最终使用了绑定。
在视图控制器中进行绑定:

class YourViewController: UIViewController {
    private lazy var guideHostingViewController = UIHostingController(rootView: UserGuideView(presentUrl: presentBinding))

    @objc private func showWebsite() {
        let navVC = UINavigationController(rootViewController: guideHostingViewController)
        present(navVC, animated: true, completion: nil)
    }
    
    private var presentBinding: Binding<URL> {
        return Binding<URL>(
            get: {
                return URL(string: "https://www.percento.app")!
            },
            set: {
                self.guideHostingViewController.present(SFSafariViewController(url: $0), animated: true, completion: nil)
            }
        )
    }
}

SwiftUI列表:

struct UserGuideView: View {
    private let guidePages: [SitePage] = [.multiCurrency, .stockSync, .dataSafety, .privacy]
    @Binding var presentUrl: URL

    var body: some View {
        VStack(alignment: .leading) {
            ForEach(guidePages) { page in
                Button(action: {
                    presentUrl = page.localiedContentUrl
                }) {
                    Text(page.description)
                        .foregroundColor(Color(UIColor.label))
                        .modifier(UserGuideRowModifier(icon: .init(systemName: page.systemIconName ?? "")))
                }
            }
            Spacer()
        }
        .padding()
        .navigationBarTitle(NSLocalizedString("User Guide", comment: "User Guide navigation bar"))
    }
}
xvw2m8pv

xvw2m8pv8#

由于这里的大多数(如果不是全部)答案都集中在SwiftUI中SFSafariViewController的模态表示上,这里有一个将其推送到NavigationView堆栈的示例(沿着在Safari中点击系统“Done”按钮时使“pop”工作):

struct ExampleView: View {
    let urls: [URL]

    var body: some View {
        NavigationView {
            List {
                ForEach(urls) { url in
                    NavigationLink(destination: {
                        SafariView(url: url)
                            .navigationBarTitleDisplayMode(.inline)
                            .ignoresSafeArea()
                    }, label: {
                        Text(url.absoluteString)
                    })
                }
            }
        }
    }
}

struct SafariView: UIViewControllerRepresentable {
    @Environment(\.dismiss) var dismiss

    let url: URL

    func makeUIViewController(context: Context) -> SFSafariViewController {
        let vc = SFSafariViewController(url: url)
        vc.preferredControlTintColor = .tintColor
        vc.delegate = context.coordinator
        return vc
    }

    func updateUIViewController(_ vc: SFSafariViewController, context: Context) {}

    class Coordinator: NSObject, SFSafariViewControllerDelegate {
        var dismissAction: DismissAction?

        func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
            dismissAction?()
        }
    }

    func makeCoordinator() -> Coordinator {
        let coordinator = Coordinator()
        coordinator.dismissAction = dismiss
        return coordinator
    }
}

相关问题