Skip to content

Instantly share code, notes, and snippets.

@KrisYu
Last active August 13, 2016 19:15
Show Gist options
  • Save KrisYu/e33ed9939c239b4c78777b79c0129391 to your computer and use it in GitHub Desktop.
Save KrisYu/e33ed9939c239b4c78777b79c0129391 to your computer and use it in GitHub Desktop.
Simple GET and Parse JSON data with dataTaskWithRequest
let firstTodoEndpoint: String = "http://jsonplaceholder.typicode.com/todos/1"
let firstTodoUrlRequest = NSMutableURLRequest(URL: NSURL(string: firstTodoEndpoint)!) firstTodoUrlRequest.HTTPMethod = "DELETE"
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(firstTodoUrlRequest) { (data, response, error) in
guard let _ = data else {
print("error calling DELETE on /todos/1")
return
}
print("DELETE ok")
}
task.resume()
override func viewDidLoad() {
super.viewDidLoad()
let todosEndPoint = "http://jsonplaceholder.typicode.com/todos"
guard let todosURL = NSURL(string: todosEndPoint) else {
print("Error: cannot create URL")
return
}
let todoUrlRequest = NSMutableURLRequest(URL: todosURL)
todoUrlRequest.HTTPMethod = "POST"
let newTodo = ["title": "First todo", "completed":false, "userId": 1]
let jsonTodo : NSData
do {
jsonTodo = try NSJSONSerialization.dataWithJSONObject(newTodo, options: [])
todoUrlRequest.HTTPBody = jsonTodo
} catch {
print("Error: cannot create JSON from todo ")
return
}
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(todoUrlRequest) { (data, response, error) in
guard error == nil else {
print("error calling GET on /todos/1")
print(error)
return
}
guard let responseData = data else {
print("Error: did not receive data")
return
}
do {
guard let todo = try NSJSONSerialization.JSONObjectWithData(responseData, options: []) as? [String: AnyObject] else {
print("error trying to convert data to JSON")
return
}
print("The to do is : " + todo.description)
guard let todoTitle = todo["title"] as? String else {
print("Could not get todo title from JSON")
return
}
print("The title is: " + todoTitle)
} catch {
print("error trying to convert data to JSON")
return
}
}
task.resume()
}
let newTodo = ["title": "Frist todo", "completed": false, "userId": 1] let jsonTodo: NSData
do {
jsonTodo = try NSJSONSerialization.dataWithJSONObject(newTodo, options: [])
todosUrlRequest.HTTPBody = jsonTodo
} catch {
print("Error: cannot create JSON from todo")
return
}
todosUrlRequest.HTTPBody = jsonTodo
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(todosUrlRequest) { (data, response, error) in
guard error == nil else {
print("error calling POST on /todos/1") print(error)
return
}
guard let responseData = data else {
print("Error: did not receive data")
return
}
// parse the result as JSON, since that's what the API provides
do {
guard let receivedTodo = try NSJSONSerialization.JSONObjectWithData(responseData, options: []) as? [String: AnyObject] else {
print("Could not get JSON from responseData as dictionary")
return
}
print("The todo is: " + receivedTodo.description)
guard let todoID = receivedTodo["id"] as? Int else { print("Could not get todoID as int from JSON") return
}
print("The ID is: \(todoID)") } catch {
print("error parsing response from POST on /todos")
return
} }
task.resume()
@KrisYu
Copy link
Author

KrisYu commented Aug 13, 2016

  • 如果只是简单的parse的话,用GET,那么使用NSURLRequest即可完成要求
  • 如果要POST的话,要使用NSMutableURLRequest,同时指定method是HTTPMethod = "POST"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment