0

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

4

3 回答 3

2

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

import PlaygroundSupport 

// [...] 

PlaygroundPage.current.needsIndefiniteExecution = true
于 2017-04-18T12:14:19.010 回答
0

请参阅代码示例:

    let zomatoKey = "<Your API Key>"        
    let centerLatitude = 19.06558, centerLongitude = 72.86215 
    let urlString = "https://developers.zomato.com/api/v2.1/search?&lat=\(centerLatitude)&lon=\(centerLongitude)";
    let url = NSURL(string: urlString)

    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 error == nil {
                let httpResponse = response as! NSHTTPURLResponse!

                if httpResponse.statusCode == 200 {
                    do {
                        if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
                            if let restaurants = json["restaurants"] as? [NSDictionary] {
                                for rest in restaurants {
                                    var searchResult = [String:AnyObject?]()
                                    let restaurant = rest["restaurant"] as! NSDictionary
                                    print(restaurant["id"] as? NSString)
                                    print(restaurant["average_cost_for_two"] as? NSNumber)
                                    print(restaurant["cuisines"] as? String)
                                    print(restaurant["url"] as? String)
                                    print(restaurant["thumb"] as? String)
                                    if let location = restaurant["location"] as? NSDictionary {
                                        print(location["address"] as? String)
                                        print(location["city"] as? String)
                                        print((location["latitude"] as? NSString).doubleValue)
                                        print((location["longitude"] as? NSString).doubleValue)
                                    }
                                    print(restaurant["menu_url"] as? String)
                                    print(restaurant["name"] as? String )
                                    print(restaurant["phone_numbers"] as? String)
                                    if let user_rating = restaurant["user_rating"] as? NSDictionary {
                                        print(user_rating["aggregate_rating"] as? NSString)
                                        print(user_rating["rating_color"] as? String)
                                        print((user_rating["votes"] as? NSNumber)).doubleValue)
                                    }
                                }
                            }
                        }

                    } catch {
                        print(error)
                    }
                }
            }
        })

        task.resume()
    }
于 2015-11-10T19:43:59.377 回答
-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
}
于 2015-11-16T20:05:21.700 回答