In Lesson 4 of Module 6 from the CodeWithChris iOS Foundation course, we learn how to retrieve data from the Yelp.com API. I’ve never used Yelp before, so don’t really know what it is, so it’s a double-learning experience for me.
There are two points of note from this lesson that I want to (b)log here for the future.
1. Creating a URL Query String
We could create the URL as a long String as we have before, only with the queries appended, but that looks unduly messy. Instead we can use urlComponents
and create the URL Query string via an array, thus:
var urlComponents = URLComponents(string: "https://api.yelp.com/v3/businesses/search")
urlComponents?.queryItems = [
URLQueryItem(name: "latitude", value: String(location.coordinate.latitude)),
URLQueryItem(name: "longitude", value: String(location.coordinate.longitude)),
URLQueryItem(name: "categories", value: category),
URLQueryItem(name: "limit", value: "6")
]
let url = urlComponents?.url
2. Fetching the Data
if let url = url {
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10.0)
request.httpMethod = "GET"
request.addValue("from Yelp.com", forHTTPHeaderField: "from Yelp.com")
let session = URLSession.shared
let dataTask = session.dataTask(with: request) { Data, response, error in
if error == nil {
print(response)
}
}
dataTask.resume()
}
The highlighted text is what we require from https://www.yelp.co.uk/developers/v3/manage_app (our API credentials).
Proxyman
The lesson also introduces us to Proxyman, which helps us to see what traffic/information is going from our app to Yelp.com, and we can immediately see what information we’re getting back, re:
{
"businesses": [
{
"id": "fTeiio1L2ZBIRdlzjdjAeg",
"alias": "alexanders-steakhouse-cupertino-11",
"name": "Alexander's Steakhouse",
"image_url": "https://s3-media4.fl.yelpcdn.com/bphoto/ZE5WP-PX9aBfKF1jorHj6A/o.jpg",
"is_closed": false,
"url": "https://www.yelp.com/biz/alexanders-steakhouse-cupertino-11?adjust_creative=EyVv075W4wvrGh0sUOGfWQ&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=EyVv075W4wvrGh0sUOGfWQ",
"review_count": 3838,
"categories": [
{
"alias": "steak",
"title": "Steakhouses"
},
{
"alias": "wine_bars",
"title": "Wine Bars"
}
],
"rating": 4.0,
"coordinates": {
"latitude": 37.3233674576911,
"longitude": -122.009842804904
},
"transactions": [
"pickup",
"delivery"
],
"price": "$$$$",
"location": {
"address1": "19379 Stevens Creek Blvd",
"address2": null,
"address3": "",
"city": "Cupertino",
...
In this instance, we can see that a JSON file is returned which we’ll be able to parse in the next lesson.