VivienG VivienG -5 years ago 177
iOS Question

POST request using alamofire 2.0 and Swift 2.0

I try to create a basic function that send a POST request using Alamofire.

@IBAction func createBasicAccount(sender: AnyObject)
var firstNameToSend = firstName.text
var lastNameToSend = lastName.text
var mailAddressToSend = mailAddress.text
var passwordToSend = password.text
var parametersToSend = [
"firstName": firstNameToSend,
"lastName": lastNameToSend,
"mailAddress": mailAddressToSend,
"password": passwordToSend

print("Account creation")

Alamofire.request(.POST, postEndpoint, parameters: parametersToSend, encoding: .JSON)

But the
won't compile and compiler returns:

Cannot convert value of type '[String : String?]' to expected argument type '[String : AnyObject]?'

I tried:

Alamofire.request(.POST, postEndpoint, parameters: parametersToSend as! AnyObject as? [String : AnyObject], encoding: .JSON)

But fails:

Account creation
Could not cast value of type 'Swift.Dictionary<Swift.String, Swift.Optional<Swift.String>>' (0x11fdb1038) to 'Swift.AnyObject' (0x12035b018).

I'm using Swift 2.0, Xcode 7.0 GM Seed, iOS 8.4 & Alamofire 2.0

Answer Source

I think that's a optional type problem. Can you try to add ! to your variables such as:

var parametersToSend = [
        "firstName": firstNameToSend!,
        "lastName": lastNameToSend!,
        "mailAddress": mailAddressToSend!,
        "password": passwordToSend!
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download