Swift 3 打开链接 [英] Swift 3 Open Link

查看:32
本文介绍了Swift 3 打开链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

然而,最后一行被标记为不能调用非函数类型UIApplication"的值.这个语法来自here,所以我不确定发生了什么.

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.

推荐答案

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

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

这篇关于Swift 3 打开链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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