0

I need to open Safari specifically, not the default browser. If Chrome/Firefox/whatever is the default browser my app still needs to open the URL in Safari.

I've looked online but all I can see is for opening in default browser like this...

let url = URL(string: host)!
NSWorkspace.shared.open(url)

...which works for me only when Safari is the users default.

How can I open a URL in Safari specifically?

Not duplicate - the other question is not in Swift...

SuperHanz98
  • 2,090
  • 2
  • 16
  • 33
  • Possible duplicate of [Open URL with Safari no matter what system browser is set to](https://stackoverflow.com/questions/2965615/open-url-with-safari-no-matter-what-system-browser-is-set-to) – Willeke Aug 14 '19 at 15:02
  • @Willeke apart from that question is in a different language? – SuperHanz98 Aug 16 '19 at 08:09

1 Answers1

0

Okay I found a solution but it's a bit of a hack...

Shell function for making bash commands:

 func shell(command: String) -> String {
    var output = ""
    var error = ""

    do {
        let task = Process()

        task.launchPath = "/bin/bash"

        task.arguments = ["-c", command]

        let outputPipe = Pipe()
        task.standardOutput = outputPipe
        let errorPipe = Pipe()
        task.standardError = errorPipe

        try task.run()
        let outputData = outputPipe.fileHandleForReading.readDataToEndOfFile()
        output = NSString(data: outputData, encoding: String.Encoding.utf8.rawValue)! as String
        let errorData = errorPipe.fileHandleForReading.readDataToEndOfFile()
        error = NSString(data: errorData, encoding: String.Encoding.utf8.rawValue)! as String
    }
    catch let err as NSError{
        output = err.localizedDescription
    }
    return error + "\n" + output + "\n"
}

In bash you can use: open -a safari www.blahblahblah.com

So in Swift I can implement this like so:

shell(command: "open -a safari " + host)

Bit of a hack but it works

SuperHanz98
  • 2,090
  • 2
  • 16
  • 33