无法转换类型'字符串的值?' (Alamofire)

时间:2016-08-01 12:53:12

标签: swift alamofire objectmapper

我使用对象映射器映射我的类User:

class User: Mappable{

private var _username: String! = nil
private var _password: String! = nil
private var _firstName: String! = nil
private var _lastName: String! = nil

//here are getters and setters(it takes too much space)

init(){

}

required init?(_ map: Map) {

}

func mapping(map: Map) {

    username <- map["USERNAME"]
    password <- map["PASSWORD"]
    firstName <- map["FIRST_NAME"]
    lastName <- map["LAST_NAME"]

  }
}

然后我尝试创建新用户并添加一些值,映射整个对象并像这样发送Alamofire:

let userEmail = userEmailField.text!
let userPassword = userPasswordField.text!

let user = User()
user.username = userEmail
user.password = userPassword
let JSONString = Mapper().toJSONString(user, prettyPrint: true)

AlamofireService.alamofireService.makePostServiceRequest(URL_BASE, parameters: JSONString, resposeCallback: self)

我按照库的说明操作,但是我收到了错误&#34;无法转换类型&#39;字符串的值?&#39;预期的参数类型&#39; [String:AnyObject]&#39;&#34;,为什么?

2 个答案:

答案 0 :(得分:4)

Alamofire请求以[String:AnyObject]格式获取参数,因此您只需要将字典作为参数传递。在你的情况下,你只需要:

let userEmail = userEmailField.text!
let userPassword = userPasswordField.text!

var dictParameter: Dictionary<String, AnyObject> = [:]
dictParameter["USERNAME"]   = userEmail
dictParameter["PASSWORD"]   = userPassword

之后只需提出请求:

AlamofireService.alamofireService.makePostServiceRequest(URL_BASE, parameters: dictParameter, resposeCallback: self)

答案 1 :(得分:0)

您不需要将参数转换为字符串,只需将参数作为字典传递给Alamofire。