在Swift中的URL上启动Safari(不是默认浏览器)? [英] Launch Safari (not default browser) at URL in Swift?

查看:146
本文介绍了在Swift中的URL上启动Safari(不是默认浏览器)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要专门打开Safari,而不是默认浏览器.如果使用Chrome/Firefox/默认浏览器,则我的应用仍需要在Safari中打开URL.

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)

...仅在用户默认使用Safari时才适用.

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

如何专门在Safari中打开URL?

How can I open a URL in Safari specifically?

不重复-另一个问题不在Swift中...

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

推荐答案

好吧,我找到了解决方案,但这有点hack ...

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

用于制作bash命令的Shell函数:

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"
}

在bash中,您可以使用: open -a safari www.blahblahblah.com

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

因此在Swift中,我可以这样实现:

So in Swift I can implement this like so:

shell(命令:"open -a safari" +主机)

有点破解,但可以正常工作

Bit of a hack but it works

这篇关于在Swift中的URL上启动Safari(不是默认浏览器)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆