[英]In Swift, how can I append a URL with a string from a UISearchbar and automatically open it in Safari?
I'm working on an app that will have a search bar where you enter text. 我正在开发一个带有搜索栏的应用程序,您可以在其中输入文本。
I'd like the app then to open "www.example.com/"entered text from search bar" but the only thing that seams to happen is it actually attempts to open www.example.com/dncode (which is not a real URL). 我希望该应用程序然后打开“ www.example.com /”(从搜索栏中输入文字),但是唯一发生的缝隙是它实际上试图打开www.example.com/dncode(这不是真正的网址)。
Any help would be greatly appreciated. 任何帮助将不胜感激。
Thanks. 谢谢。
import UIKit
class ViewController: UIViewController, UISearchBarDelegate {
//connection that ties search bar in view to input for viewcontroller
@IBOutlet weak var searchbar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
searchbar.delegate = self
}
//activates keyboard etc when searchbar clicked
func searchBarSearchButtonClicked(_ searchbar: UISearchBar) {
searchbar.resignFirstResponder()
//(dncode) is string that will equal text as entered into search bar
let dncode = String()
searchbar.text! = dncode
if let url = URL (string: "https://www.example.com/(dncode)")
{
//this section to check and auto open URL in default browser "Safari"
if #available(iOS 10.0, *)
{
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
}
}
You are setting the text of search bar equal to your dncode variable and not viceversa. 您正在将搜索栏的文本设置为等于dncode变量,而不是相反。 You have to change your implementation:
您必须更改实现:
func searchBarSearchButtonClicked(_ searchbar: UISearchBar) {
searchbar.resignFirstResponder()
//(dncode) is string that will equal text as entered into search bar
guard let dncode = searchbar.text else { return }
if let url = URL (string: "https://www.example.com/(dncode)") {
//this section to check and auto open URL in default browser "Safari"
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
}
You must replace: 您必须更换:
let dncode = String()
searchbar.text! = dncode
if let url = URL (string: "https://www.example.com/(dncode)")
by 通过
guard let dncode = searchbar.text else { return }
if let url = URL (string: "https://www.example.com/\(dncode)")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.