How to use responseDecodable instead of responseJSON using Alamofire 6 - ios

One of my apps no longer works due to JSON serialisation failing when using Alamofire.
'responseJSON(queue:dataPreprocessor:emptyResponseCodes:emptyRequestMethods:options:completionHandler:)'
is deprecated: responseJSON deprecated and will be removed in
Alamofire 6. Use responseDecodable instead.
For code with the following lines
AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: [:]).responseJSON { response in.. }
When changing to
AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: [:])
.responseDecodable { response in... }
Then I get the error
Generic parameter 'T' could not be inferred
So I add the following
AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: [:])
.responseDecodable(of: ResponseType.self) { response in.. }
I get the error
Cannot find 'ResponseType' in scope
Does anyone have any suggestions?

Unlike .responseJSON which returns a dictionary or array .responseDecodable deserializes the JSON into structs or classes.
You have to create an appropriate model which conforms to Decodable, in your code it's represented by ResponseType(.self).
The associated value of the success case is the root struct of the model.
But deprecated (in a yellow warning) means the API is still operational.
Side note: A JSON dictionary is never [String: Any?] the value is always non-optional.

In Alamofire -> Documentation/Usage.md, I found the definition of the Decodable, so I try like this, then found working.
struct DecodableType: Decodable {
let url: String
}
AF.request(urlString).responseDecodable(of: DecodableType.self) { response in
switch response.result {
case .success(let dTypes):
print(dTypes.url)
case .failure(let error):
print(error)
}
}

Related

How to handle empty response using Alamofire and Combine?

I am making a post request, which has an empty response
AF.request(URL(string: "some url")!, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: nil)
.validate()
.publishDecodable(type: T.self)
.value()
.eraseToAnyPublisher()
where T is
struct EmptyResponse: Codable {}
and I am having this error "Response could not be serialized, input data was nil or zero length."
How do I handle a post request with an empty response using Alamofire and Combine?
This error occurs when your backend returns no data but does not return an appropriate HTTP response code (204 or 205). If this is expected behavior for your backend, you can add your response code to the list of acceptable empty response codes when you set up the publisher: .publishDecodable(T.self, emptyResponseCodes: [200]. This also requires T to either conform to Alamofire's EmptyResponse protocol, or for you to expect Alamofire's Empty type as the response.
Found answer somewhere else but it's useful here. Made empty object like that:
struct EmptyEntity: Codable, EmptyResponse {
static func emptyValue() -> EmptyEntity {
return EmptyEntity.init()
}
}
And return publisher like so:
-> AnyPublisher<EmptyEntity, AFError>
AF.request(UrlUtils.base_url, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response:AFDataResponse<Any>) in
switch(response.result) {
case .success(_):
// this case handles http response code 200, so it will be a successful response
break
case .failure(_):
break
}
}

Alamofire post request error Extra argument 'method' in call

I'm using xcode 9.2 I want to make a post request however I'm getting this error "Extra argument 'method' in call". I know it's talking about the post method but i dont know how to fix it, can anyone help?
Alamofire.request(URL_REGISTER, method: .post, parameters: body, encoding: JSONEncoding, headers: header).responseString {
(response) in
if response.results.error == nil {
completion(true)
} else {
completion(false)
debugPrint(response.resultd.error as Any)
}
}
your attributes probably aren't valid (if the types don't match Xcode will tell you the error with the closest matching function)
try changing JSONEncoding to JSONEncoding.default and that your body matches [String:Any]
Alamofire.request(String, method: HTTPMethod.post, parameters: [String:Any], encoding: JSONEncoding.default, headers: header)
something along these lines (I don't know about the header attribute I usually have this at nil)
It probably is because your body variable isn't [String: Any]

Setting content-type header to use JSON with Swift 3 + AlamoFire

The answers in Alamofire Swift 3.0 Extra parameter in call did not work for me.
Setting header to nil compiles but I need ["Content-Type", "application/json"]. Here I get an error of an extra parameter in th emethod
How do I take
manager.request(url, method: .get, parameters: parameters).responseJSON {
response in
fulfill(response)
}
}
and send JSON content-type?
The documentation shows
Automatic Validation
Automatically validates status code within 200..<300 range, and that the Content-Type header of the response matches the Accept header of the request, if one is provided.
Alamofire.request("https://httpbin.org/get").validate().responseJSON { response in
switch response.result {
case .success:
print("Validation Successful")
case .failure(let error):
print(error)
}
}
I'm using .responseJSON but I'm not getting JSON back. So I think I need to send the Content-Type header.
Try this, there is another method overload that allow pass a dictionary with headers
let request = Alamofire.request(requestUrl, method: .get, parameters: [:], encoding: URLEncoding.queryString, headers: ["Content-Type" :"application/json"]).responseData { (response) in
/***YOUR CODE***/
}
for post JSON data in request check this answer Using manager.request with POST
Hope this helps you

Alamofire extra argument 'method' in call from Alamofire example

I would like to state that I've tried every single example and scanned the plethora of other questions exactly like mine to no avail, so I have NO CHOICE but to post.
Xcode: 8.3.1 (8E1000a)
Apple Swift version 3.1 (swiftlang-802.0.51 clang-802.0.41)
Target: x86_64-apple-macosx10.9
OSX 10.12.4
Please see the code:
Note: This is embedded in a function, the parameters "email" and "password" are strings and are available, I also tried setting static string values.
let url = URL(string: "http://website.what.com/api/v1/login")
let params: Parameters = ["email": email, "password":password]
// This Works
Alamofire.request(url!, method: .post, parameters: params)
.responseJSON { response in
switch response.result {
case .success:
print(response)
case .failure(let error):
print(error)
}
}
// This one returns: "Extra argument Method in call"
let parameters: Parameters = [
"foo": [1,2,3],
"bar": [
"baz": "qux"
]
]
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON { response in
switch response.result {
case .success:
print(response)
case .failure(let error):
print(error)
}
}
The primary I am confident in posting again - the second example was taken straight from the Alamofire github README.
If I am missing something - as in incorrectly encoding a parameter (which I copied directly from Alamofire's github page) or something.
Alternately, if someone can provide me a working sample on Swift 3.1 which allows me to use JSON, Headers, and POST Method.
The first "working" method does not have headers, I am not sure if I can use that example with additional parameters or not?
Sorry for the trouble, very very fresh swift learner who is diving head-first into a complicated world.

Alamofire v4 extra argument method in call error

Once I updated to alamofire version 4 I get the error: extra argument method in call
Alamofire.request("www.blabla", method: .put, parameters: parameters, headers: headers, encoding: .JSON)
I already changed it to use "method: .put" like above but I still get the error
I had this issue upgrading to Alamofire 4 and solved it by moving the headers argument and making it the last argument in the call. Also encoding: .JSON should be encoding: JSONEncoding.default.
Call should look like this:
Alamofire.request(url: myUrl, method: .put, parameters: myParams,
encoding: JSONEncoding.default, headers: myHeaders)
What type is parameters? It has to be at least [:] - like:
Alamofire.request(url: myUrl, method: .put, parameters: [:], encoding: JSONEnconding.default, headers: myHeaders)
I broke mind into URLRequest and then just the Alamofire call. Nothing I found worked except breaking it up. I'm using Swift 3 and XCode 8.2.1 and I believe this is swift's sourceKit getting an object wrong.
this
Alamofire.request(url:treeURL!, method: .get, parameters: [:], encoding: JSONEncoding.default, headers: ["Authorization" : app.getToken()])
became this:
var request = URLRequest(url: treeURL!)
request.httpMethod = "GET"
request.allHTTPHeaderFields = ["Authorization" : app.getToken()]
Alamofire.request(request as URLRequestConvertible)
Alamofire.request( "http://....", method: .put , parameters: parameters, encoding: JSONEncoding.default).responseJSON{
response in
if response.result.isSuccess {
//some code
}
}

Resources