使用alamofire 2.0和Swift 2.0的POST请求

时间:2015-09-16 06:33:46

标签: ios swift2 alamofire

我尝试创建一个使用Alamofire发送POST请求的基本功能。

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

但是Alamofire.request将无法编译并且编译器返回:

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

我试过了:

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

但失败了:

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

我正在使用 Swift 2.0 Xcode 7.0 GM Seed iOS 8.4 &amp; Alamofire 2.0

2 个答案:

答案 0 :(得分:13)

我认为这是一个可选的类型问题。你能尝试添加!你的变量,如:

var parametersToSend = [
        "firstName": firstNameToSend!,
        "lastName": lastNameToSend!,
        "mailAddress": mailAddressToSend!,
        "password": passwordToSend!
    ]

答案 1 :(得分:0)

这是SWIFT最新的VERIOSN代码2.2希望它能为您带来...... 这是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)")
            }
    }