【发布时间】:2016-11-24 19:38:15
【问题描述】:
我有这个 API http://my-api.mydoctorfinder.com/ 这将根据您输入的电子邮件和密码返回一个布尔值。
我的问题是,尽管使用了正确的电子邮件和密码,但它总是会返回 false。
我在想我可能没有发送正确的参数,因为我创建了一个包含电子邮件和密码的字典。然后通过 NSJSONSerialization.dataWithJSONObject 方法传递它
顺便说一句,我使用的是 SwiftyJson。
这是我的代码
//creates a dictionary and calls the PostRequest method
func attemptLogIn( email: String, password: String) {
let route = loggerURL
let body: [String:String] = ["email":email, "password":password]
makeHTTPPostRequest(route, body: body)
}
//performs post request
private func makeHTTPPostRequest(path: String, body: [String: AnyObject]) {
let request = NSMutableURLRequest(URL: NSURL(string: path)!)
// Set the method to POST
request.HTTPMethod = "POST"
do {
// Set the POST body for the request
let jsonBody = try NSJSONSerialization.dataWithJSONObject(body, options: .PrettyPrinted)
request.HTTPBody = jsonBody
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if let jsonData = data {
let json:JSON = JSON(data: jsonData)
//onCompletion(json, nil)
print("The Response: ")
print(json)
} else {
//onCompletion(nil, error)
print("The Response: ")
print("Hello")
}
})
task.resume()
} catch {
// Create your personal error
//onCompletion(nil, nil)
}
}
【问题讨论】:
-
您的 API 文档并没有立即表明它是期待
application/json请求、application/x-www-form-urlencoded请求还是 XML 或其他什么。 (仅仅因为您可能会生成 JSON 响应,并不一定意味着请求也是 JSON。)您的代码建议请求应该是 JSON,但如果是这样,您应该相应地设置Content-Type标头,如所述约西普。顺便说一句,你说它“总是返回 [s] false”。response是什么样的?error?如果 JSON 解析失败,data包含什么?
标签: ios json xcode swift2 swifty-json