如何在Swift中发布请求

时间:2016-07-21 09:32:27

标签: ios json xcode swift2 swifty-json

我有这个API http://my-api.mydoctorfinder.com/ 这将返回一个bool值,具体取决于您输入的电子邮件和密码。

我的问题是,尽管使用了正确的电子邮件和密码,它总是会返回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)
    }
}

4 个答案:

答案 0 :(得分:2)

响应只是一个真或假,即它不是一个json对象。 所以我建议不要使用Swifty儿子而不是使用Alamofire。

以下代码应该适合您: -

let myParameters = [
    "email": "your email id",
    "password": "your password"]

Alamofire.request(.POST, "http://my-api.mydoctorfinder.com/ ", parameters: myParameters)
         .response { request, response, data, error in
              print(request)
              print(response)
if(response == true)
{
// do your thing
}
              print(error)
          }

注意:可能需要对bool进行类型转换

以下是您提供的链接的屏幕截图,它返回true(而不是json对象)[注册后,我尝试使用相同的凭据登录]

enter image description here

答案 1 :(得分:1)

尝试以这种方式使用NSJSONSerialization创建JSON对象:

request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(body, options: [])

我认为问题出在.PrettyPrinted常量。

编辑: 另外,请尝试添加正确的内容类型:

request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

答案 2 :(得分:1)

以下是获取数据的快速发布请求:

func retriveTextDataByPost(requestURL:String, params: NSDictionary, handler:((dict:NSDictionary?) -> Void)) {

    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)

    let url = NSURL(string: requestURL)
    let request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 60)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.HTTPMethod = "POST"

    do {
        let postData = try NSJSONSerialization.dataWithJSONObject(params, options:NSJSONWritingOptions.PrettyPrinted)
        request.HTTPBody = postData

        let postDataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in

            if data != nil {

                do {

                    let dictResult:NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
                    handler(dict: dictResult)

                } catch { }
            }
        }
        postDataTask.resume()

    } catch { }
}

答案 3 :(得分:-1)

  1. 使用API​​的必需输入检查您的密钥是否有电子邮件和密码
  2. 检查您的登录网址