iOS http POST使用Alamofire

时间:2015-10-31 16:35:38

标签: swift alamofire

我需要一些帮助,使用Alamofire通过Twilio的API使用用户名/密码对网页进行POST。

我之前使用过GitHub的SwiftRequest,但这不支持Swift 2.0。

我使用的代码(使用SwiftRequest)是:

        var data = [
            "To" : mobileInput.text as String!,
            "From" : twilioSMSFrom,
            "Body" : String(code) as String
        ]

        var swiftRequest = SwiftRequest()

        swiftRequest.post("https://api.twilio.com/2010-04-01/Accounts/\(twilioUsername)/Messages",
            auth: ["username" : twilioUsername, "password" : twilioPassword],
            data: data,
            callback: {err, response, body in
                if err == nil {
                    println("Success: \(response)")
                } else {
                    println("Error: \(err)")
                }
            })

如何将其翻译为使用Alamofire?

我尝试过搜索解决方案,但可以找到。

有人能帮助我吗?

3 个答案:

答案 0 :(得分:1)

尝试这样的事情:

Alamofire.request(.POST, "https://api.twilio.com/2010-04-01/Accounts/\(twilioUsername)/Messages", parameters: ["username": twilioUsername, "password" : twilioPassword])
     .responseJSON { response in
         print(response.request)
         print(response.response)
         print(response.result)

         if let JSON = response.result.value {
             print("Did receive JSON data: \(JSON)")
         }
         else {
             print("JSON data is nil.")
         }

      }

你一定要查看他们的github页面 - https://github.com/Alamofire/Alamofire

答案 1 :(得分:1)

我明白了。

使用Alamofire的解决方案:

        let data = [
            "To" : mobileInput.text as String!,
            "From" : twilioSMSFrom,
            "Body" : String(code) as String
        ]

        Alamofire.request(.POST, "https://\(twilioUsername):\(twilioPassword)@api.twilio.com/2010-04-01/Accounts/\(twilioUsername)/Messages", parameters: data)
            .responseJSON { response in
                print(response.request)
                print(response.response)
                print(response.result)
        }

答案 2 :(得分:0)

这是SWIFT 2.2 VERSION的最新答案 尝试这个可以帮助你......

参数: -

    let params : Dictionary = ["YourKEY" : "YourVALUE"]

发布Request_Form: -

Alamofire.request(.POST,"Post Your Url HERE", parameters: params, encoding:.JSON).responseJSON
        {
          response in switch response.result 
            {
                  case .Success(let JSON):
         //   print("Success with JSON: \(JSON)")
            //converting json into NSDictionary

            let response = JSON as! NSDictionary
            print(response)

            var array = NSMutableArray!()
            //converting respose form into NSMutableArray formate
            array = response.valueForKey("countryList")as? NSMutableArray

            //example if there is an id
          //  let userId = response.objectForKey("id")!

        case .Failure(let error):
            print("Request failed with error: \(error)")
            }
    }