我正在开发一个可以在其中输入文字的搜索栏的应用。
我希望应用程序然后打开“www.example.com/”来自搜索栏的“来自文本”,但唯一接触的是它实际上尝试打开www.example.com/dncode(这是不是真正的网址。)
非常感谢任何帮助。
感谢。
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)
}
}
}
}
答案 0 :(得分:0)
您将搜索栏的文本设置为等于您的dncode变量,而不是反之亦然。 你必须改变你的实施:
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)
}
}
}
答案 1 :(得分:0)
您必须替换:
let dncode = String()
searchbar.text! = dncode
if let url = URL (string: "https://www.example.com/(dncode)")
通过
guard let dncode = searchbar.text else { return }
if let url = URL (string: "https://www.example.com/\(dncode)")