我尝试将JSON发布到我的网络服务器中,但它根本不起作用。它适用于" DELETE"和" GET" ,但对于" POST"它根本不工作并得到错误。
这是我的代码:
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()
我收到错误"解析来自/ categories"
的POST响应 你可以帮我吗?答案 0 :(得分:2)
你说:
我尝试将JSON发布到我的网络服务器中,但它根本不起作用
在查看代码时,我们确实知道两件事。
你正在考虑你的NSJSONSerialization,所以你要好好直到那一点。现在你只需要调整你的序列化类型,你应该(也许)是好的。
您需要将post
类型更改为[[String:AnyObject]]
,因为我们会在您尝试捕获时将其更改为
let post: [[String:AnyObject]]
do {
post = try NSJSONSerialization.JSONObjectWithData(responseData,
options: .MutableLeaves) as! [[String:AnyObject]]
} catch {
print("error parsing response from POST on /categories")
return
}
当你以这种方式这样做时,通过将你的帖子传递到这样的函数很容易获得你的返回值:
func valuesFromData(jsonDict: [[String:AnyObject]]) {
let myValue = jsonDict["key"] as? String
let another = jsonDict["SomeOtherKey"] as? Int
}
如果您仍然遇到问题,只需打印我们的状态代码即可查看您的POST无效的原因。在完成处理程序(闭包)内部添加以下内容:
guard let status = response.statusCode as? NSHTTPURLResponse else {
return
}
print("status code: \(status)")
这是一个完美工作的NSURLRequest
的例子func postNewMessage(messageType: String, messageBody: String) {
guard let token = AppDelegate.userDefaults.valueForKey("token") else {
return
}
let params = [
"messageType": messageType,
"messageBody": messageBody
]
var jsonData: NSData?
var jsonString: NSString?
var tokenResponse: String?
do {
jsonData = try NSJSONSerialization.dataWithJSONObject(params, options: [])
} catch {
print(error)
return
}
let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:8080/messages")!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
request.addValue(token as! String, forHTTPHeaderField: "user-auth-token")
request.HTTPBody = jsonData!
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
guard let testResponse = response as? NSHTTPURLResponse else {
print("failed \(response)")
return
}
guard let status = HTTPStatusCodes(rawValue: testResponse.statusCode) else {
print("failed again")
return
}
switch status {
case .Created:
let headerFields = testResponse.allHeaderFields
tokenResponse = headerFields["user-auth-token"] as? String
guard let returnedData = data else {
print("no data was returned")
break
}
// convert data to string
jsonString = NSString(data: returnedData, encoding: NSUTF8StringEncoding) ?? "Invalid JSON"
print("\(tokenResponse)\n\n\(jsonString!)")
// update user interface
dispatch_sync(dispatch_get_main_queue()) {
print("derp")
}
default:
print("asdf")
}
}
task.resume()
}
您还需要使用此枚举才能使其正常运行。
enum HTTPStatusCodes : Int {
case Ok = 200
case Created = 201
case BadRequest = 404
}
(简化的)