Skip to content

Instantly share code, notes, and snippets.

@jineshpaloor
Last active November 6, 2015 12:30
Show Gist options
  • Save jineshpaloor/8d5a34806ce835992105 to your computer and use it in GitHub Desktop.
Save jineshpaloor/8d5a34806ce835992105 to your computer and use it in GitHub Desktop.
-------------------------------------------------------------------------------------
// using alamofire
Alamofire.request(.GET, Constants.Keys.BASE_URL+"/giftcards", headers: header, encoding: .JSON).validate().responseJSON() { response in
if let error = response.result.error {
self.fetchFailure(error.code, errorBody: error.description)
return
}
let json = JSON(response.result.value!)
self.ownedGiftcards.removeAll()
self.receivedGiftcards.removeAll()
self.awaitingAcceptanceGiftcards.removeAll()
self.buildGiftCardsList(json)
self.fetchSuccess()
}
------------------------------------------------------------------------
// using NSURL: https://grokswift.com/simple-rest-with-swift/
func getNearestLocations(latitude: Double, longitude: Double, brandId: String) {
print("requesting nearest locations")
print("inside test api")
let postEndpoint: String = "http://jsonplaceholder.typicode.com/posts/1"
print(postEndpoint)
guard let url = NSURL(string: postEndpoint) else {
print("Error: cannot create URL")
return
}
print("got url")
let urlRequest = NSURLRequest(URL: url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
print("lets enter task")
let task = session.dataTaskWithRequest(urlRequest, completionHandler: {
(data, response, error) in
print("inside task completion handler")
guard let responseData = data else {
print("Error: did not receive data")
return
}
guard error == nil else {
print("error calling GET on /posts/1")
print(error)
return
}
// parse the result as JSON, since that's what the API provides
let post: NSDictionary
do {
post = try NSJSONSerialization.JSONObjectWithData(responseData,
options: []) as! NSDictionary
} catch {
print("error trying to convert data to JSON")
return
}
// now we have the post, let's just print it to prove we can access it
print("The post is: " + post.description)
// the post object is a dictionary
// so we just access the title using the "title" key
// so check for a title and print it if we have one
if let postTitle = post["title"] as? String {
print("The title is: " + postTitle)
}
})
print("task definition over")
task.resume()
print("task resume completed")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment