xcode Swift 3 打开链接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39402696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:13:02  来源:igfitidea点击:

Swift 3 Open Link

iosxcodehyperlinkswift3

提问by Alex

I'm trying to run this function when a button is tapped:

我正在尝试在点击按钮时运行此功能:

@IBAction func openLink(_ sender: UIButton) {
    let link1 = "https://www.google.com/#q="
    let link2 = birdName.text!
    let link3 = link2.replacingOccurrences(of: " ", with: "+") //EDIT
    let link4 = link1+link3
    guard
        let query = link4.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed),
        let url = NSURL(string: "https://google.com/#q=\(query)")
        else { return }
    UIApplication.shared.openURL(URL(url))
}

However, the last line is flagged as "cannot call value of non-function type "UIApplication". This syntax is from here, so I'm not sure whats going on.

但是,最后一行被标记为“无法调用非函数类型“UIApplication”的值。此语法来自此处,因此我不确定发生了什么。

回答by Leo Dabus

Use guard to unwrap the textfield text property, replacing the occurrences, add percent encoding to the result and create an URL from the resulting string:

使用 guard 来解开 textfield 文本属性,替换出现的内容,向结果添加百分比编码并从结果字符串创建一个 URL:

Try like this:

像这样尝试:

guard
    let text = birdName.text?.replacingOccurrences(of: " ", with: "+"),
    let query = text.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
    let url = URL(string: "https://google.com/#q=" + query)
else { return }
if #available(iOS 10.0, *) {
    UIApplication.shared.open(url)
} else {
    UIApplication.shared.openURL(url)
}