我嘗試將JSON發佈到我的Web服務器,但它根本不起作用。它適用於「DELETE」和「GET」,但對於「POST」它根本不起作用並獲取錯誤。如何將數據序列化爲JSON對象
這是我的代碼:
let postsEndpoint:String = "http://ideabase.herokuapp.com/categories"
guard let postsURL = NSURL(string: postsEndpoint) else {
print("Error: cannot create URL")
return
}
let postsUrlRequest = NSMutableURLRequest(URL: postsURL)
postsUrlRequest.HTTPMethod = "POST"
let newPost: NSDictionary = ["id":7, "title": "Purple","created_at": "2015-12-08 08:06:55","updated_at":"2015-12-08 08:06:55"]
do {
let jsonPost = try NSJSONSerialization.dataWithJSONObject(newPost, options: [])
postsUrlRequest.HTTPBody = jsonPost
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let createTask = session.dataTaskWithRequest(postsUrlRequest, completionHandler: {
(data, response, error) in
guard let responseData = data else {
print("Error: did not receive data")
return
}
guard error == nil else {
print("error calling GET on /categories/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 parsing response from POST on /categories")
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 postID = post["id"] as? Int
{
print("The ID is: \(postID)")
}
})
createTask.resume()
我得到的錯誤 「解析響應從POST上/類別」
你能幫幫我嗎?
嘗試使用查爾斯或其他代理,可以讓你看到所有的HTTP流量將在/你的系統。然後,您可以確保該信息是您所期望的,並查看有關回復的詳細信息。 – farhadf
@Gharay,我已經添加了一個工作POST請求的示例 –