2016-09-09 41 views
0

我试图运行此函数当按钮被窃听。斯威夫特3中打开链接

@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’这语法是从这里,所以我不知道怎么回事

+0

这会导致应用程序崩溃时按下按钮“意外地发现零,同时解包可选值” – Alex

+0

请确保您使用正确的URL链接。您可能必须转义您的查询字符串% –

+0

我试过浏览器上的链接,并且链接很好。什么是百分比逃脱? – Alex

回答

7

使用保护解开文本字段text属性,替换出现,加上百分号编码的结果和产生的字符串创建一个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) 
} 
+1

我真的很感谢像你这样的人帮助像我们这样没有那么受过教育的错误和问题的人们。你真的帮助我们谋生! – Honey

+0

@霍尼谢谢很高兴帮助。不用谢。 –