如何在SwiftUI中使用SFSafariViewController?

时间:2019-06-09 20:10:00

标签: ios swift safari swiftui

我正在尝试展示SFSafariViewController中的NavigationButton,但是我不确定如何使用SwiftUI。

在UIKit中,我会这样做:

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

    present(vc, animated: true)

7 个答案:

答案 0 :(得分:4)

有时候答案是不使用SwiftUI! 这在UIKit中得到了很好的支持,以至于我只是一个通向UIKit的简单桥梁,因此我可以像下面这样在SwiftUI的一行中调用SafariController:

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

我只是将应用程序顶层的UIHostingController替换为HSHostingController

(请注意-该类还允许您控制模态的表示样式)

//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

答案 1 :(得分:2)

SFSafariViewControllerUIKit的组成部分,因此您需要使其成为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应当显示在另一个视图控制器的顶部,而不是推入导航堆栈中。

它还有一个导航栏,这意味着如果按下视图控制器,您将看到两个导航栏。

enter image description here

如果出现毛刺,它似乎可以工作-尽管出现毛刺-

struct ContentView : View {

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

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

它看起来像这样:

enter image description here

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

答案 2 :(得分:1)

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>) {

    }

}

答案 3 :(得分:1)

使用 BetterSafariView ,您可以在SwiftUI中轻松显示SFSafariViewController。它可以按照Apple的预期运行良好,而不会丢失其原始的推入过渡和滑动到关闭手势。

用法

.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
                )
            )
        }
    }
}

答案 4 :(得分:0)

这是使用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)
        }
    }
}

答案 5 :(得分:0)

在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造成任何重大变化。

-Jakub

答案 6 :(得分:0)

以上都不适合我,因为我试图在按钮列表中显示 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"))
    }
}