Skip to content

Instantly share code, notes, and snippets.

@kaiobrito
Last active January 4, 2017 03:10
Show Gist options
  • Save kaiobrito/c966bbd84ce586e29ea0564c304c4f7c to your computer and use it in GitHub Desktop.
Save kaiobrito/c966bbd84ce586e29ea0564c304c4f7c to your computer and use it in GitHub Desktop.
protocol JSONMappable {
init(json: JSON)
}
struct GHUser: JSONMappable {
var login: String
var id: String
init(json: JSON) {
self.login = json["login"].stringValue
self.id = json["id"].stringValue
}
}
struct GHRepository: JSONMappable {
var id: String
var name: String
init(json: JSON) {
self.name = json["name"].stringValue
self.id = json["id"].stringValue
}
}
class SearchableWebService<T: JSONMappable> {
typealias SearchResponseHandler = (([T]) -> Void)
func searchURL(withTerm term: String) -> URL {
fatalError()
}
func search(term: String, handler: SearchResponseHandler? = nil) {
let url = self.searchURL(withTerm: term)
let task = URLSession.shared.dataTask(with: url) { data, _ , _ in
if let data = data {
let json = JSON(data: data)
handler?(json["items"].arrayValue.map(T.init))
}
}
task.resume()
}
}
class GHRepositoryWebService: SearchableWebService<GHRepository> {
override func searchURL(withTerm term: String) -> URL {
return URL(string:"https://api.github.com/search/repositories?q=\(term)")!
}
}
class GHUserWebService: SearchableWebService<GHUser> {
override func searchURL(withTerm term: String) -> URL {
return URL(string:"https://api.github.com/search/users?q=\(term)")!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment