【问题标题】:Make POST request with alamofire使用 alamofire 发出 POST 请求
【发布时间】:2015-04-05 03:44:24
【问题描述】:

我是我的 swift 应用程序。我想用 alamofire 创建一个请求 POST

请求

$ 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 

我的代码

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)
                      }
      }

我遇到了这个错误

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.)"})

【问题讨论】:

    标签: swift alamofire


    【解决方案1】:

    如果您使用真机进行测试,则应将主机从 localhost 更改为您的 Mac 的 IP 地址,并确保您的 iPhone 和 Mac 在同一个无线网络中。

    如果您使用模拟器进行测试,它应该可以工作。也许您可以将localhost 更改为127.0.0.1。

    错误是由于错误的 url。您可以在设备中的 Safari 中进行测试,看看它是否有效。

    【讨论】:

    • 这很棒。我在我的 iPhone 上测试 localhost,它总是会失败。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-19
    • 2020-02-10
    • 2018-10-25
    • 2018-07-27
    • 1970-01-01
    • 2015-11-23
    • 2018-04-10
    相关资源
    最近更新 更多