2017-10-21 84 views
0

我正在研究一个应用程序,该应用程序将在您输入文本的地方有一个搜索栏。在Swift中,如何在UISearchbar中添加一个包含字符串的URL并在Safari中自动打开它?

我想要应用程序然后打开“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) 
    } 
} 
} 
} 
+0

我不明白什么是DNCODE在你的代码,它只是连接空字符串?你能给更多的精度吗?您想在Safari中打开哪个网址? – iLandes

回答

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

如果让url = URL(字符串:“https://www.example.com/(dncode)”),您还必须替换:if let url = URL(string:“https://www.example.com/ \(DNCODE)“) – iLandes

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)") 
相关问题