Swift 3 Open Link

Ale*_*lex 0 xcode hyperlink ios swift3

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

@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))
}
Run Code Online (Sandbox Code Playgroud)

但是,最后一行被标记为"无法调用非函数类型的值"UIApplication".这个语法来自这里,所以我不确定它们是怎么回事.

Leo*_*bus 8

使用guard展开textfield文本属性,替换出现次数,将百分比编码添加到结果中,并从结果字符串创建URL:

试试这样:

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)
}
Run Code Online (Sandbox Code Playgroud)

  • 我真的很感谢像你这样的人帮助像我们这样的人解决我们不那么受过教育的错误和问题。你真的是在帮助我们谋生! (2认同)