简体   繁体   English

使用alamofire发出POST请求

[英]Make POST request with alamofire

I my swift app . 我是我的快速应用程序。 I want to create a request POST with alamofire 我想用alamofire创建一个请求POST

The request 要求

$ curl \
          -H 'Accept: application/json' \
          -H 'Content-Type: application/json' \
          -X POST -d '{ "user": { "email": "user@example.com", "password": "1234" } }' \
          http://localhost:3000/users/sign_in 

My code 我的密码

let crendetials = ["user": ["email": "bolo@me.com", "password": "PASSWORD"]]
              var postsEndpoint: String = "http://localhost:3000/users/sign_in"
             Alamofire.request(.POST, postsEndpoint, parameters: crendetials, encoding: .JSON)
                  .responseJSON { (request, response, data, error) in
                      if let anError = error
                      {
                          // got an error in getting the data, need to handle it
                          println("error calling POST on /users/sign_in")
                          println(error)
                      }
                      else if let data: AnyObject = data
                      {
                          // handle the results as JSON, without a bunch of nested if loops
                          let post = JSON(data)
                          // to make sure it posted, print the results
                          println(data)
                      }
      }

I have got this error 我有这个错误

request: <NSMutableURLRequest: 0x170208be0> { URL: http://localhost:3000/users/sign_in } || response: nil || object: Optional(<>) || error: Optional(Error Domain=NSURLErrorDomain Code=-1004 "The operation couldn’t be completed. (NSURLErrorDomain error -1004.)" UserInfo=0x1740f6900 {NSErrorFailingURLStringKey=http://localhost:3000/users/sign_in, NSErrorFailingURLKey=http://localhost:3000/users/sign_in, _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=61, NSUnderlyingError=0x17405c500 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1004.)"})

If you're testing with a real iPhone, you should change the host from localhost to your Mac's ip address and make sure you iPhone and Mac in the same wireless network. 如果您正在使用真实的iPhone进行测试,则应将主机从localhost更改为Mac的IP地址,并确保iPhone和Mac在同一无线网络中。

If you're testing with a simulator, it should work. 如果您正在使用模拟器进行测试,那么它应该可以工作。 Maybe you can change localhost to 127.0.0.1 . 也许您可以将localhost更改为127.0.0.1

The error is due to wrong url. 该错误是由于网址错误引起的。 You can test in Safari in your device to see if it works. 您可以在设备的Safari中进行测试,以查看其是否正常运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM