我正在开发一个应用程序,该应用程序将有一个搜索栏,您可以在其中输入文本。
我希望应用程序打开“www.example.com/”从搜索栏输入的文本”,但唯一发生的事情是它实际上尝试打开 www.example.com/dncode (这是不是真实的 URL)。
任何帮助将不胜感激。
谢谢。
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)
}
}
}
}
最佳答案
您必须替换:
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)")
关于ios - 在 Swift 中,如何在 URL 中附加 UISearchbar 中的字符串并在 Safari 中自动打开它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46866330/