Swift 3打开链接
我试图在点击button时运行这个函数:
@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)) }
但是,最后一行被标记为“不能调用非函数types的值”UIApplication“。这个语法是从这里开始的,所以我不确定是怎么回事。
使用guard来展开textfield文本属性,replace出现的地方,将百分号编码添加到结果中,并从结果string中创build一个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) }