How do I create a Safari View in SwiftUI that uses a custom user agent?

1.3k Views Asked by At

I’m trying to create a SwiftUI app that uses a Safari view using the SafariServices framework and assign a custom user agent to that view so that websites believe that the web browser is Safari for macOS, when I’m really using Safari for iOS on iPhone.

Here’s the Safari view that I wrapped using UIKit:

struct SafariView: UIViewControllerRepresentable {
    
    let url: String
    
    func makeUIViewController(context: UIViewControllerRepresentableContext<SafariView>) -> SFSafariViewController {
        
        var safariViewController = SFSafariViewController(url: URL.init(string: url)!)
        
        safariViewController.preferredBarTintColor = .systemBackground
        safariViewController.configuration.entersReaderIfAvailable = false
        safariViewController.dismissButtonStyle = .close
        
        return safariViewController

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

I can’t seem to figure out what I need to do to apply a custom user agent. I’m sure I need to add something in the makeUIViewController function, but I have no clue what attribute I need to use. Can someone help me please?

1

There are 1 best solutions below

0
On

A SFSafariViewController really is an instance of Safari, with full access to all of its features so you are not allowed to change the user agent. However if you need this functionality you can use WKWebView instead and set customUserAgent.