0

With the Zomato API key, how do you authenticate, search for restaurants and parse the data?

CamQuest
  • 833
  • 9
  • 16

3 Answers3

2

If running your code on Playground, need to add following:

import PlaygroundSupport 

// [...] 

PlaygroundPage.current.needsIndefiniteExecution = true
goto
  • 7,908
  • 10
  • 48
  • 58
jet.lau
  • 21
  • 4
0

See code sample:

    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()
    }
CamQuest
  • 833
  • 9
  • 16
-1

This was my implementation assuming you have a class Restaurants

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
}
Steven Sajja
  • 33
  • 2
  • 7