从searchBar中获取文本并使其在URL中可用

时间:2018-01-11 23:00:34

标签: ios swift

我正在尝试创建一个应用程序,以便从myanimelist.net查看动漫。我编写了代码来解析文本并显示数据,但到目前为止它只显示来自特定URL的数据,如

https://myanimelist.net/api/anime/search.xml?q=sword+art+online

我正在尝试将searchBar文本传递到我拥有链接的位置,以便它一次动态搜索而不是只搜索一个动画,例如

https://myanimelist.net/api/anime/search.xml?q=(search term here)

这是URL为

的代码
private func fetchData()
    {
        let feedParser = FeedParser()
        feedParser.parseFeed(url: "https://myanimelist.net/api/anime/search.xml?q=")
            {
            (animeItems) in
                self.animeItems = animeItems
                OperationQueue.main.addOperation
                    {
                    self.tableView.reloadSections(IndexSet(integer: 0), with: .left)
                    }
            }
    }

这是我在TableViewController中搜索URL的代码。

这是XMLparser.swift中处理HTTP身份验证的位

   func parseFeed(url: String, completionHandler: (([AnimeItem]) -> Void)?)
    {
        self.parserCompletionHandler = completionHandler


        //task.resume()
        let username = "MALPocket"
        let password = "qpwoeiruty"
        let logindata = String(format : "%@:%@", username, password).data(using: String.Encoding.utf8)!
        let base64String = logindata.base64EncodedString()
        var request = URLRequest(url: URL(string: url)!)
        request.httpMethod = "GET"
        request.setValue("Basic \(base64String)", forHTTPHeaderField: "Authorization")

        let urlSession = URLSession.shared
        let task = urlSession.dataTask(with: request) { (data, response, error) in
            guard let data = data else
            {
                if let error = error
                {
                    print(error.localizedDescription)
                }

                return
            }
            print(data)

            /// parse the xml data
            let parser = XMLParser(data: data)
            parser.delegate = self
            parser.parse()
        }



        task.resume()
    }

我尝试过像

这样的事情
  func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)
    {
    }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar, textDidChange searchText: String)
    {
        self.tableView.reloadData()
    }

并尝试将searchText保存到变量以添加到链接上,如

feedParser.parseFeed(url: "https://myanimelist.net/api/anime/search.xml?q=\(searchText)")

但我尝试的所有内容都以未解决的标识符错误或更糟糕的方式结束。

2 个答案:

答案 0 :(得分:1)

很难确切地说出错误是什么,但您可能需要对搜索字词进行编码,以便可以将其与网址中的查询一起使用。幸运的是,Swift对此内置支持:

let encodedSearchTerm = searchText.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
feedParser.parseFeed(url: "https://myanimelist.net/api/anime/search.xml?q=\(encodedSearchTerm)") { animeItems in
// Do something with your animeItems
}

这是一个如何在视图控制器中使用它的示例。我不知道你的设置是什么样的,所以这可能会有所不同,所以这只是一个例子:

class MyViewController: UIViewController, UISearchBarDelegate {

    @IBOutlet var searchBar: UISearchBar!

    private let feedParser = FeedParser()

    override func viewDidLoad() {
        super.viewDidLoad()
        searchBar.delegate = self
    }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        let searchText = searchBar.text ?? ""
        let encodedSearchTerm = searchText.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
        feedParser.parseFeed(url: "https://myanimelist.net/api/anime/search.xml?q=\(encodedSearchTerm)") { animeItems in
            // Do something with your animeItems
        }
    }

}

答案 1 :(得分:0)

管理修复它,这是代码。

override func viewDidLoad()
{
    super.viewDidLoad()
    searchBar.delegate = self

    fetchData(searchTerm: nil)
    tableview.reloadData()
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)
{
    print("search Text: \(searchText)")
}

func searchBarSearchButtonClicked(_ searchBar: UISearchBar)
{
    self.fetchData(searchTerm: searchBar.text)
}


func fetchData(searchTerm: String?)
{
    var components = URLComponents(string: "https://myanimelist.net/api/anime/search.xml")

    if let searchTerm = searchTerm {
        components?.queryItems = [URLQueryItem(name: "q", value: searchTerm)]
    }

    guard let urlString = components?.url?.absoluteString else { return }
    feedParser.parseFeed(url: urlString){ (animeItems) in
            self.animeItems = animeItems
            OperationQueue.main.addOperation
                {
                self.tableView.reloadSections(IndexSet(integer: 0), with: .left)
                }
        }
}

在此搜索工作之后,由于数组没有重置,因此无法正常进行第二次搜索,因此我还在此添加到我的解析器代码中以删除数组并重新开始,现在搜索的工作原理。

animeItems.removeAll()