从REST API for iOS app获取数据

时间:2016-01-05 18:45:41

标签: ios api rest

这是我第一次使用Swift并创建iOS应用程序,但我无法从REST API中检索数据。我熟悉Android开发,但不熟悉iOS。

我正在尝试使用www.thecocktaildb.com.

中的API

请求的示例是http://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita

我想使用此请求并从搜索栏输入字符串margarita或任何其他饮品名称,然后将饮料数组显示在tableview中。

现在,当我跑步时,我没有从控制台得到任何回应。

我是否在正确的轨道上?

我也不确定如何在表格视图单元格中显示每个结果(饮料)。

这是我的档案:

SearchViewController.swift

class SearchViewController: UIViewController, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var TableView: UITableView!
    @IBOutlet weak var SearchBar: UISearchBar!

    // search in progress or not
    var isSearching : Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()

        for subView in self.SearchBar.subviews
        {
            for subsubView in subView.subviews
            {

                if let textField = subsubView as? UITextField
                {
                    textField.attributedPlaceholder  = NSAttributedString(string: NSLocalizedString("Search", comment: ""))

                }
            }
        }

        // set search bar delegate
        self.SearchBar.delegate = self
    }

    func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {

        if self.SearchBar.text!.isEmpty {

            // set searching false
            self.isSearching = false

        }else{

            // set searghing true
            self.isSearching = true

            let postEndpoint: String = "http://www.thecocktaildb.com/api/json/v1/1/search.php?s=" + self.SearchBar.text!.lowercaseString

            guard let url = NSURL(string: postEndpoint) else {
                print("Error: cannot create URL")
                return
            }

            let urlRequest = NSURLRequest(URL: url)
            let config = NSURLSessionConfiguration.defaultSessionConfiguration()
            let session = NSURLSession(configuration: config)

            let task = session.dataTaskWithRequest(urlRequest, completionHandler: { (data, response, error) in
                guard let responseData = data else {
                    print("Error: did not receive data")
                    return
                }
                guard error == nil else {
                    print("error calling GET on www.thecocktaildb.com")
                    print(error)
                    return
                }
                // parse the result as JSON, since that's what the API provides
                let post: NSDictionary
                do {
                    post = try NSJSONSerialization.JSONObjectWithData(responseData,
                        options: []) as! NSDictionary
                } catch  {
                    print("error trying to convert data to JSON")
                    return
                }

                if let strDrink = post["strDrink"] as? String {
                    print("The drink is: " + strDrink)
                }
            })
            task.resume()

        }
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    }

    // hide kwyboard when search button clicked
    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        self.SearchBar.resignFirstResponder()
    }

    // hide keyboard when cancel button clicked
    func searchBarCancelButtonClicked(searchBar: UISearchBar) {
        self.SearchBar.text = ""
        self.SearchBar.resignFirstResponder()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

1 个答案:

答案 0 :(得分:0)

使用提供的网址http://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita

分析从GET请求收到的json
{
  "drinks":[{ ... }]
}

有一个drinks密钥,因此您应该在尝试访问json的更深层次之前导航到它。另请注意,drinks值是一个JSON数组,应该强制转换为[NSDictionary]

下面的代码可以帮助您开始使用它。

if let drinks = post["drinks"] as? [NSDictionary] {
    for drink in drinks {
        if let strDrink = drink["strDrink"] as? String {
            print("The drink is: " + strDrink)
        }
    }
}