Reputation:
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?
Upvotes: 0
Views: 1398
Reputation: 15669
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
}
Upvotes: 0
Reputation: 8020
You value in your dictionary is an Optional type. You should be able to get rid of the error if you unwrap it with a bang !
Upvotes: 0
Reputation: 1712
I believe you need to unpack the text fields! This has happened to me a LOT since converting to Swift 2. Might be worth a try
let parameters = [
"fullname": fullName.text!,
"username": username.text!,
"email": email.text!,
"password": password.text!,
"country": country
]
Upvotes: 1