Skip to content

Instantly share code, notes, and snippets.

@koogawa
Created March 13, 2017 09:06
Show Gist options
  • Save koogawa/31d8d7ca757d7961fbc5f8c2fea8aa78 to your computer and use it in GitHub Desktop.
Save koogawa/31d8d7ca757d7961fbc5f8c2fea8aa78 to your computer and use it in GitHub Desktop.
Get category id from category name
class Category: CustomStringConvertible {
var id: String
var name: String
init(id: String, name: String) {
self.id = id
self.name = name
}
var description: String {
return "id=\(id), name=\(name)\n"
}
}
class ViewController: UIViewController {
var filteredCategories: Array<Category> = []
override func viewDidLoad() {
super.viewDidLoad()
self.jsonParser()
}
func jsonParser() {
let urlPath = "https://api.foursquare.com/v2/venues/categories?oauth_token=(YOUR_TOKEN)&v=20170313"
guard let endpoint = URL(string: urlPath) else {
print("Error creating endpoint")
return
}
URLSession.shared.dataTask(with: endpoint) { [weak self] (data, response, error) in
guard let data = data else {
print("No data")
return
}
guard let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
print("Error parsing JSON")
return
}
if let response = json?["response"] as? [String:Any],
let categories = response["categories"] as? [[String: Any]],
let strongSelf = self {
strongSelf.filter(categories: categories, keyword: "restaurant")
print("Result: ", strongSelf.filteredCategories)
}
}.resume()
}
func filter(categories: [[String:Any]], keyword: String) {
for category in categories {
guard let id = category["id"] as? String,
let name = category["name"] as? String else {
continue
}
if name.lowercased().contains(keyword) {
let filteredCategory = Category(id: id, name: name)
self.filteredCategories.append(filteredCategory)
}
if let subCategories = category["categories"] as? [[String: Any]] {
self.filter(categories: subCategories, keyword: keyword)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment