Search code examples
iosswiftswift2alamofire

Alamofire String is not identical to AnyObject error


I use Alamofire in Swift 2. So, I have parameters:

let parameters = [
        "fullname": fullName.text,
        "username": username.text,
        "email": email.text,
        "password": password.text,
        "country": country
    ]

and send request via:

Alamofire.request(Method.POST, "http://myapi.mysite.com/users", parameters: parameters)
            .response { request, response, data, error in

but it returns me the next error, that parameters

'String?' is not identical to 'AnyObject'

How can I fix it?


Solution

  • If we look into Alamofire closely, we'll find that the method request looks like this:

    public func request(
        method: Method,
        _ URLString: URLStringConvertible,
        parameters: [String: AnyObject]? = nil,
        encoding: ParameterEncoding = .URL,
        headers: [String: String]? = nil)
        -> Request
    

    So we can see, that parameters is of type [String : AnyObject]?, which is optional itself, but only the array as a whole. The parameters inside cannot be optional. Your parameters you're adding to the dictionary are optional, so it's necessary to unwrap them. It is fairly common to use the safety structures in Swift, so forcing ! just to surpass the compiler is not the smartest option. Use if-let for handling it:

    if let fullname = fn.text, un = username.text, em = email.text, pwd = password.text {
        let parameters = [
            //...
        ]
    } else {
        // handle the situation - inform the user they forgot some fields
    }
    

    As for your Cannot call value of non-function type 'NSHTTPURLResponse?' problem:

    The issue is with Alamofire 2.0 migration where the response serialization has rapidly changed, so for your case use it like this:

    Alamofire.request(.POST, "https://myapi.mysite.com/users", parameters: parameters) 
        .responseJSON { _, _, result in 
            print(result) 
            // mumbo jumbo
    }