Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

ios - Swift 3 Open Link

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

Try like this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...