1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SwiftUIでSFSafariViewControllerコーディングを簡単に行う

Posted at

demo.gif

SFSafariViewControllerはナビゲーション時の振る舞いや状態管理を自身で有しているので、予めUIViewControllerRepresentable化してSwiftUIで制御しようとするとコーディングが複雑になる。なのでそれを簡単に行えるパターンを考えてみた。

import SwiftUI
import SafariServices

public struct RepresentControllerView: UIViewControllerRepresentable {
    private var uiViewController: UIViewController
    
    public init(uiViewController: UIViewController) {
        self.uiViewController = uiViewController
    }
    
    public func makeUIViewController(context: Context) -> UIViewController {
        uiViewController
    }
    
    public func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}
}

public final class HostingController<Content: View>: UIHostingController<Content>, ObservableObject {}

public struct HostingControllerView<Content: View>: View {
    private var c: HostingController<Content>
    
    public init(rootView: Content) {
        self.c = HostingController(rootView: rootView)
    }
    
    public var body: some View {
        RepresentControllerView(uiViewController: c).environmentObject(c)
    }
}

struct ContentView: View {
    struct RootView: View {
        @EnvironmentObject var viewController: HostingController<RootView>
        private let urlString = "https://example.org"
        func present() {
            let safari = SFSafariViewController(url: URL(string: urlString)!)
            viewController.present(safari, animated: true, completion: nil)
        }
        var body: some View {
            Button(urlString, action: present)
        }
    }
    var body: some View {
        HostingControllerView(rootView: RootView())
    }
}

期待通りウェブをフルスクリーンモーダルで表示が出来た。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?