Skip to content

Instantly share code, notes, and snippets.

@willrichman
Created October 22, 2014 21:05
Show Gist options
  • Save willrichman/66d5b13a18db43297480 to your computer and use it in GitHub Desktop.
Save willrichman/66d5b13a18db43297480 to your computer and use it in GitHub Desktop.
Search function resusable
func search (searchString: String, type: SearchType, completionHandler: (returnedArray: [AnyObject], errorDescription: String?) -> Void) {
let searchReposURL = "https://api.github.com/search/repositories?q="
let searchUsersURL = "https://api.github.com/search/users?q="
let cleanedSearch = searchString.stringByReplacingOccurrencesOfString(" ", withString: "+", options: nil, range: nil)
var url : NSURL?
switch type {
case .Repos:
url = NSURL(string: (searchReposURL + cleanedSearch))?
case .Users:
url = NSURL(string: (searchUsersURL + cleanedSearch))?
default:
println("That is not a valid search type")
}
let task = self.networkSession!.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
if let httpResponse = response as? NSHTTPURLResponse {
if error != nil {
// If there is an error in the web request, print to console
println(error.localizedDescription)
}
switch httpResponse.statusCode {
case 200...299:
println("Success!!")
var returnedArray : [AnyObject]?
switch type {
case .Repos:
let returnedArray = Repo.parseJSONDataIntoRepos(data)
case .Users:
let returnedArray = User.parseJSONDataIntoUsers(data)
default:
println("Something bad happened")
}
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
completionHandler(returnedArray: returnedArray!, errorDescription: nil)
})
case 400...499:
println("error on the client")
println(httpResponse.description)
case 500...599:
println("error on the server")
default:
println("something bad happened")
}
}
else {
println("Something bad happened")
}
})
task.resume()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment