如何使用Zomato API验证和解析数据

时间:2015-11-10 19:43:59

标签: swift zomato-api

使用Zomato API密钥,您如何进行身份验证,搜索餐馆并解析数据?

3 个答案:

答案 0 :(得分:2)

如果在Playground上运行代码,需要添加以下内容:

import PlaygroundSupport 

// [...] 

PlaygroundPage.current.needsIndefiniteExecution = true

答案 1 :(得分:0)

参见代码示例:

>>> g = ((n, s) for n, s in [("A", 1), ("B", 2), ("C", 3), ("D", 4), ("E", 5)])
>>> pd.DataFrame(g).set_index(0)[1]
0
A    1
B    2
C    3
D    4
E    5
Name: 1, dtype: int64

答案 2 :(得分:-1)

这是我的实现,假设您有一个类餐厅

func getRestaurants() {

    let url = NSURL(string: zomatoURLString)

    if url != nil {
        let request = NSMutableURLRequest(URL: url!)
        request.HTTPMethod = "GET"
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        request.addValue(zomatoKey, forHTTPHeaderField: "user_key")

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {
            (data,response,error) -> Void in

            if let error = error {
                print(error)
                return
            }

            //Parse Json data

            if let data = data {
                self.restaurants = self.parseJsonData(data)

                //reload table
                NSOperationQueue.mainQueue().addOperationWithBlock({() -> Void in
                    self.tableView.reloadData()
                })

            }
        })

        task.resume()

    }
}


func parseJsonData(data: NSData) -> [Restaurant] {

    do {
        let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary

        //Parse JSON DATA
        let jsonRestaurants = jsonResult?["restaurants"] as! [AnyObject]

        for res in jsonRestaurants {
            let restaurant = Restaurant()
            let myRestaurant = res["restaurant"] as! NSDictionary
            restaurant.restaurantName = myRestaurant["name"] as! String
            restaurant.restaurantType = myRestaurant["cuisines"] as! String
            restaurant.restaurantImage = myRestaurant["thumb"] as! String
            let location = myRestaurant["location"] as! [String: AnyObject]
            restaurant.restaurantLocation = location["address"] as! String
            restaurants.append(restaurant)
        }
    } catch {
        print(error)
    }
    return restaurants
}