Eirik Madland Eirik Madland - 5 months ago 51
Swift Question

iOS http POST using Alamofire

I need some help using Alamofire to do a POST to a web page using a username/password throug an API from Twilio.

I have used SwiftRequest from GitHub before, but that doesn't support Swift 2.0.

The code I used (using SwiftRequest) was:

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


How can I translate this to use Alamofire instead?

I have tried searching for a solution, but could find any.

Can anybody help me?

Answer

I figured it out.

The solution using 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)
        }
Comments