2015-04-05 141 views
2

我的swift應用程序。我想創建一個信息發佈與alamofire使用alamofire發送POST請求

請求

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

我的代碼

let crendetials = ["user": ["email": "[email protected]", "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.)"}) 

回答

5

如果你和一個測試真正的iPhone,您應該將主機從localhost更改爲您的Mac的IP地址,並確保您iPhone和Mac在同一無線網絡中。

如果您使用模擬器進行測試,它應該可以工作。也許你可以將localhost更改爲127.0.0.1

錯誤是由於錯誤的網址。您可以在設備上的Safari中進行測試,看看它是否有效。

+0

這太好了。我在我的iPhone上測試localhost,它總是會失敗。 – OlivaresF 2015-05-18 21:26:03