Skip to content

Instantly share code, notes, and snippets.

@tarrouye
Last active June 28, 2023 22:51
Show Gist options
  • Save tarrouye/517ef7587abc6668da42620203adf995 to your computer and use it in GitHub Desktop.
Save tarrouye/517ef7587abc6668da42620203adf995 to your computer and use it in GitHub Desktop.
Present SFSafariViewController as a NavigationController from SwiftUI.
//
// UIApplication+Safari.swift
// DoraDora
//
// Created by Théo Arrouye on 5/12/23.
//
import SafariServices
import UIKit
extension UIApplication {
var firstKeyWindow: UIWindow? {
return UIApplication.shared.connectedScenes
.compactMap { $0 as? UIWindowScene }
.filter { $0.activationState == .foregroundActive }
.first?.keyWindow
}
func showSafariView(url: URL?) {
guard let url else { return }
let vc = SFSafariViewController(url: url)
firstKeyWindow?.rootViewController?.present(vc, animated: true)
}
}
@tarrouye
Copy link
Author

tarrouye commented Jun 28, 2023

Use it in your views like so:

// This button will present an SFSafariController as a navigation controller when tapped. 
Button {
  UIApplication.shared.showSafariView(url: item.destinationURL)
} label: {
  ItemView(item: item)
} 

Using this method avoids weird issues with double navigation bars, etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment