2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SFSafariViewControllerをUIKitと同じ挙動でSwiftUIで使用する方法

Last updated at Posted at 2023-08-16

ネットの文献にはモーダルで表示する方法しか書かれておらず、push遷移の動作が実現できなかったので、今回はSwiftUIでSFSafariViewControllerをpush遷移のような動作で表示する方法を解説していきたいと思います。

実装

SFSafariView.swift
import SwiftUI
import SafariServices

struct SFSafariViewControllerWrap: UIViewControllerRepresentable {
    @Environment(\.dismiss) var dismiss
    let url: URL

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

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

    func makeCoordinator() -> Coordinator {
        Coordinator(parent: self)
    }

    final class Coordinator: NSObject, SFSafariViewControllerDelegate {
        let parent: SFSafariViewControllerWrap

        fileprivate init(parent: SFSafariViewControllerWrap) {
            self.parent = parent
        }

        func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
            parent.dismiss()
        }
    }
}

struct SFSafariView: View {
    let url: URL

    var body: some View {
        SFSafariViewControllerWrap(url: url)
            .toolbar(.hidden, for: .navigationBar)
            .ignoresSafeArea(.all)
    }
}

使用方法

HogeView.swift
struct HogeView: View {
    @State var isPresented = false

    var body: some View {
        FugaView()
            .navigationDestination(isPresented: $isPresented) {
                SFSafariView(url: URL(string: "https://google.com")!)
            }
    }
}

これでモーダル遷移ではなくpush遷移でSFSafariViewControllerを表示することができました。

2
4
1

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
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?