【问题标题】:Swift 3 Open LinkSwift 3 打开链接
【发布时间】:2017-01-17 01:55:57
【问题描述】:

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

@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))
}

但是,最后一行被标记为“不能调用非函数类型“UIApplication”的值。这个语法来自这里,所以我不确定发生了什么。

【问题讨论】:

  • 这会导致应用程序在按下按钮时崩溃“在展开可选值时意外发现 nil”
  • 确保您使用的是正确的 url 链接。您可能必须对查询字符串进行百分比转义
  • 我在浏览器上试过链接,链接很好。什么是逃逸百分比?
  • 解决了!谢谢!

标签: ios swift xcode hyperlink


【解决方案1】:

使用 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)
}

【讨论】:

  • 我非常感谢像你这样的人帮助像我们这样的人解决我们没有受过教育的错误和问题。你真的在帮助我们谋生!
猜你喜欢
  • 2017-08-17
  • 1970-01-01
  • 2017-03-08
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 2017-07-19
  • 1970-01-01
相关资源
最近更新 更多