I have a get method with 3 parameters on the base url itself.I have tried the following code, but it is going to failure condition saying either not a valid url or not a valid JSON.
What is the correct way to approach this?
The code i have used is as below:
let header: HTTPHeaders = ["Content-Type":"application/json","x-token":self.token!]
let todosEndpoint: String = "https://reachwebdemo.com/2020/10/listcribdev/api/chatnotification?" + "channel_sid=\(self.channelsid!)&author=\(self.userid!)&message=\(inputMessage)"
if let encoded = todosEndpoint.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed),let url = URL(string: encoded)
{
print("notify url is",url)
AF.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: header).responseString { response in
switch response.result {
case .success(let json):
print("Validation Successful for push notification",json)
case let .failure(error):
print("error for push notificaton",error.errorDescription)
}
}
}
You user parameters like url and it's wrong way to make request like this.
You need add parameters on request method like parameters. And yes, you can use parameters on 'GET' requests.
let header: HTTPHeaders = ["Content-Type":"application/json","x-token":self.token!]
let todosEndpoint: String = "https://reachwebdemo.com/2020/10/listcribdev/api/chatnotification"
let params:[String: Any] = ["channel_sid":self.channelsid!, "author":self.userid!, "message": inputMessage]
if let encoded = todosEndpoint.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed),
let url = URL(string: encoded) {
print("notify url is",url)
AF.request(url, method: .get, parameters: params, encoding: URLEncoding.default, headers: header).responseString { response in
switch response.result {
case .success(let json):
print("Validation Successful for push notification",json)
case let .failure(error):
print("error for push notificaton",error.errorDescription)
}
}
}
I want to post some xml to an url. This is my code:
func post(){
var data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Devices><Device><ID>EZR0114AF</ID><HEATAREA nr=\"4\"><T_TARGET>17.0</T_TARGET></HEATAREA></Device></Devices>"
Alamofire.request(urlPost, .post, parameters: data, encoding: .utf8, headers: nil).response { (response) in
print(response.data)
print(response.error)
print(response.response)
}
}
But I get a Syntax error: Extra argument in call. I have no idea what is missing, I tried a lot but nothing works. Any ideas?
Try changing the syntax to
let urlString = "XXXXXXXXX"
Alamofire.request(urlString, method: .post, parameters: ["id": "1,2,3,4"] ,encoding: JSONEncoding.default, headers: nil).responseString {
response in
switch response.result {
case .success(let responseString1):
print("the response is: \(responseString1)")
break
case .failure(let error):
print("The error is: \(error)")
}
}
I am trying to use JSONDecoder to decode a json response from my server using Alamofire. When I decode the response with a guard, it works without any issues. The side-effect of this approach is that I can't tell what the issue is when the decode actually fails.
guard let result: TResponseData = try? decoder.decode(TResponseData.self, from: response.data!) else {
self.logger.error("Unable to decode the response data into a model representation.")
return
}
So instead I'm wanting to use a do { } catch { } but I can't figure out how exactly I'm supposed to use it within the Alamofire responseJSON callback.
This is what I've currently got:
Alamofire.request(completeUrl, method: .post, parameters: parameters, encoding: encoding, headers: headers)
.validate()
.responseJSON { (response) -> Void in
self.logger.info("POST Response: \(String(describing:response.response?.statusCode))")
switch response.result {
case .success(_):
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .custom(Date.toTMDBDate)
do {
let _ = try decoder.decode(TResponseData.self, from: response.data!)
} catch DecodingError.dataCorrupted(let error) {
self.logger.error(error.underlyingError)
return
}
completion(result)
return
case .failure(let error):
//....
}
What I am given with this code however is a compiler error on the .responseJSON { (response) -> Void in line.
Invalid conversion from throwing function of type '(_) -> Void' to non-throwing function type '(DataResponse) -> Void'.
The guard code works fine, and if I change the try to a try? or force an unwrap, it compiles - I just don't get to have my catch handle the actual error.
If I change the catch block so that it does not include any pattern, then the code compiles.
catch {
return
}
This doesn't give me anything over what my guard was giving me. I really want to capture the error encountered with the decode operation. Am I using the wrong pattern? Why does using the DecodingError.dataCorrupted pattern seemingly change the callback signature?
JSONDecoder can throw errors other than DecodingError.dataCorrupted; you need to be able to handle the case of an arbitrary Error being thrown. So, if you want to handle that error, you'll want an unconditional catch {} block.
You can also:
Use responseData instead of responseJSON as you're doing your own deserialisation with JSONDecoder.
Use the unwrap() method on Alamofire's Result type in order to coalesce the network error with the decoding error, if desired.
This is what that looks like:
Alamofire
.request(
completeUrl, method: .post, parameters: parameters,
encoding: encoding, headers: headers
)
.validate()
.responseData { response in
self.logger.info(
"POST Response: \(response.response?.statusCode as Any)"
)
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .custom(Date.toTMDBDate)
do {
let result = try decoder.decode(
TResponseData.self, from: response.result.unwrap()
)
completion(result)
} catch {
self.logger.error(error)
}
}
Although one thing to note here is that you're not calling completion if the request fails; I would personally change that such that you do, and propagate the error back by having the completion take a Result<TResponseData> parameter.
In that case, you can use Result's flatMap(_:) method rather than unwrap() and a catch {} block:
func doRequest(_ completion: #escaping (Result<TResponseData>) -> Void) {
let completeURL = // ...
let parameters = // ...
let encoding = // ...
let headers = // ...
Alamofire
.request(
completeURL, method: .post, parameters: parameters,
encoding: encoding, headers: headers
)
.validate()
.responseData { response in
self.logger.info(
"POST Response: \(response.response?.statusCode as Any)"
)
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .custom(Date.toTMDBDate)
// if response.result is successful data, try to decode.
// if decoding fails, result is that error.
// if response.result is failure, result is that error.
let result = response.result.flatMap {
try decoder.decode(TResponseData.self, from: $0)
}
.ifFailure {
self.logger.error($0)
}
completion(result)
}
}
I'm very new to Swift 3, and i have to do a GET request on my API. I'm using Alamofire, which uses Asynchronous functions.
I do exactly the same on my Android App, and the GET returns JSON data
This is my code in swift :
func getValueJSON() -> JSON {
var res = JSON({})
let myGroup = DispatchGroup()
myGroup.enter()
Alamofire.request(url_).responseJSON { response in
res = response.result.value as! JSON
print("first result", res)
myGroup.leave()
}
myGroup.notify(queue: .main) {
print("Finished all requests.", res)
}
print("second result", res)
return res
}
But i have a problem with the line "res = response.result.value" wich gives me the error : Thread 1 : signal SIGABRT
I really don't understand where the problem comes from, it was pretty hard to do a "synchronous" function, maybe i'm doing it wrong.
My objective is to store the result of the request in a variable that i return. Anyone can help ?
I'd recommend you to use Alamofire together with SwiftyJSON because that way you'll be able to parse JSON easier a lot.
Here's a classical example:
Alamofire.request("http://example.net", method: .get).responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
print("JSON: \(json)")
case .failure(let error):
print(error)
}
}
If you need to pass parameters, or headers, just add it in the request method.
let headers: HTTPHeaders = [
"Content-Type:": "application/json"
]
let parameters: [String: Any] = [
"key": "value"
]
So your request will be something like this (this is POST request):
Alamofire.request("http://example.net", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
switch response.result {
case .success(let value):
print(value)
case .failure(let error):
print(error)
}
}
I haven't tested it, but it should work. Also, you need to set allow arbitary load to yes (App Transport Security Settings in info.plist) if you want to allow requests over HTTP protocol.
This is NOT recommended, but it's fine for development.
I would like to retrieve the HTTP response status code (e.g. 400, 401, 403, 503, etc) for request failures (and ideally for successes too). In this code, I am performing user authentication with HTTP Basic and want to be able to message the user that authentication failed when the user mistypes their password.
Alamofire.request(.GET, "https://host.com/a/path").authenticate(user: "user", password: "typo")
.responseString { (req, res, data, error) in
if error != nil {
println("STRING Error:: error:\(error)")
println(" req:\(req)")
println(" res:\(res)")
println(" data:\(data)")
return
}
println("SUCCESS for String")
}
.responseJSON { (req, res, data, error) in
if error != nil {
println("JSON Error:: error:\(error)")
println(" req:\(req)")
println(" res:\(res)")
println(" data:\(data)")
return
}
println("SUCCESS for JSON")
}
Unfortunately, the error produced does not seem to indicate that an HTTP status code 409 was actually received:
STRING Error:: error:Optional(Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo=0x7f9beb8efce0 {NSErrorFailingURLKey=https://host.com/a/path, NSLocalizedDescription=cancelled, NSErrorFailingURLStringKey=https://host.com/a/path})
req:<NSMutableURLRequest: 0x7f9beb89d5e0> { URL: https://host.com/a/path }
res:nil
data:Optional("")
JSON Error:: error:Optional(Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo=0x7f9beb8efce0 {NSErrorFailingURLKey=https://host.com/a/path, NSLocalizedDescription=cancelled, NSErrorFailingURLStringKey=https://host.com/a/path})
req:<NSMutableURLRequest: 0x7f9beb89d5e0> { URL: https://host.com/a/path }
res:nil
data:nil
Additionally, it would be nice to retrieve the HTTP body when an error occurs because my server-side will put a textual description of the error there.
Questions
Is it possible to retrieve the status code upon a non-2xx response?
Is it possible to retrieve the specific status code upon a 2xx response?
Is it possible to retrieve the HTTP body upon a non-2xx response?
Thanks!
For Swift 3.x / Swift 4.0 / Swift 5.0 users with Alamofire >= 4.0 / Alamofire >= 5.0
response.response?.statusCode
More verbose example:
Alamofire.request(urlString)
.responseString { response in
print("Success: \(response.result.isSuccess)")
print("Response String: \(response.result.value)")
var statusCode = response.response?.statusCode
if let error = response.result.error as? AFError {
statusCode = error._code // statusCode private
switch error {
case .invalidURL(let url):
print("Invalid URL: \(url) - \(error.localizedDescription)")
case .parameterEncodingFailed(let reason):
print("Parameter encoding failed: \(error.localizedDescription)")
print("Failure Reason: \(reason)")
case .multipartEncodingFailed(let reason):
print("Multipart encoding failed: \(error.localizedDescription)")
print("Failure Reason: \(reason)")
case .responseValidationFailed(let reason):
print("Response validation failed: \(error.localizedDescription)")
print("Failure Reason: \(reason)")
switch reason {
case .dataFileNil, .dataFileReadFailed:
print("Downloaded file could not be read")
case .missingContentType(let acceptableContentTypes):
print("Content Type Missing: \(acceptableContentTypes)")
case .unacceptableContentType(let acceptableContentTypes, let responseContentType):
print("Response content type: \(responseContentType) was unacceptable: \(acceptableContentTypes)")
case .unacceptableStatusCode(let code):
print("Response status code was unacceptable: \(code)")
statusCode = code
}
case .responseSerializationFailed(let reason):
print("Response serialization failed: \(error.localizedDescription)")
print("Failure Reason: \(reason)")
// statusCode = 3840 ???? maybe..
default:break
}
print("Underlying error: \(error.underlyingError)")
} else if let error = response.result.error as? URLError {
print("URLError occurred: \(error)")
} else {
print("Unknown error: \(response.result.error)")
}
print(statusCode) // the status code
}
(Alamofire 4 contains a completely new error system, look here for details)
For Swift 2.x users with Alamofire >= 3.0
Alamofire.request(.GET, urlString)
.responseString { response in
print("Success: \(response.result.isSuccess)")
print("Response String: \(response.result.value)")
if let alamoError = response.result.error {
let alamoCode = alamoError.code
let statusCode = (response.response?.statusCode)!
} else { //no errors
let statusCode = (response.response?.statusCode)! //example : 200
}
}
In the completion handler with argument response below I find the http status code is in response.response.statusCode:
Alamofire.request(.POST, urlString, parameters: parameters)
.responseJSON(completionHandler: {response in
switch(response.result) {
case .Success(let JSON):
// Yeah! Hand response
case .Failure(let error):
let message : String
if let httpStatusCode = response.response?.statusCode {
switch(httpStatusCode) {
case 400:
message = "Username or password not provided."
case 401:
message = "Incorrect password for user '\(name)'."
...
}
} else {
message = error.localizedDescription
}
// display alert with error message
}
Alamofire
.request(.GET, "REQUEST_URL", parameters: parms, headers: headers)
.validate(statusCode: 200..<300)
.responseJSON{ response in
switch response.result{
case .Success:
if let JSON = response.result.value
{
}
case .Failure(let error):
}
Best way to get the status code using alamofire.
Alamofire.request(URL).responseJSON {
response in
let status = response.response?.statusCode
print("STATUS \(status)")
}
Or use pattern matching
if let error = response.result.error as? AFError {
if case .responseValidationFailed(.unacceptableStatusCode(let code)) = error {
print(code)
}
}
you may check the following code for status code handler by alamofire
let request = URLRequest(url: URL(string:"url string")!)
Alamofire.request(request).validate(statusCode: 200..<300).responseJSON { (response) in
switch response.result {
case .success(let data as [String:Any]):
completion(true,data)
case .failure(let err):
print(err.localizedDescription)
completion(false,err)
default:
completion(false,nil)
}
}
if status code is not validate it will be enter the failure in switch case
In your responseJSON completion, you can get the status code from the response object, which has a type of NSHTTPURLResponse?:
if let response = res {
var statusCode = response.statusCode
}
This will work regardless of whether the status code is in the error range. For more information, take a look at the NSHTTPURLResponse documentation.
For your other question, you can use the responseString function to get the raw response body. You can add this in addition to responseJSON and both will be called.
.responseJson { (req, res, json, error) in
// existing code
}
.responseString { (_, _, body, _) in
// body is a String? containing the response body
}
Your error indicates that the operation is being cancelled for some reason. I'd need more details to understand why. But I think the bigger issue may be that since your endpoint https://host.com/a/path is bogus, there is no real server response to report, and hence you're seeing nil.
If you hit up a valid endpoint that serves up a proper response, you should see a non-nil value for res (using the techniques Sam mentions) in the form of a NSURLHTTPResponse object with properties like statusCode, etc.
Also, just to be clear, error is of type NSError. It tells you why the network request failed. The status code of the failure on the server side is actually a part of the response.
Hope that helps answer your main question.
I needed to know how to get the actual error code number.
I inherited a project from someone else and I had to get the error codes from a .catch clause that they had previously setup for Alamofire:
} .catch { (error) in
guard let error = error as? AFError else { return }
guard let statusCode = error.responseCode else { return }
print("Alamofire statusCode num is: ", statusCode)
}
Or if you need to get it from the response value follow #mbryzinski's answer
Alamofire ... { (response) in
guard let error = response.result.error as? AFError else { return }
guard let statusCode = error.responseCode else { return }
print("Alamofire statusCode num is: ", statusCode)
})
For Swift 2.0 users with Alamofire > 2.0
Alamofire.request(.GET, url)
.responseString { _, response, result in
if response?.statusCode == 200{
//Do something with result
}
}
For Swift 3.x / Swift 4.0 / Swift 5.0 users with Alamofire >= 5.0
Used request modifier to increase and decrease the timeout interval.
Alamofire's request creation methods offer the most common parameters for customization but sometimes those just aren't enough. The URLRequests created from the passed values can be modified by using a RequestModifier closure when creating requests. For example, to set the URLRequest's timeoutInterval to 120 seconds, modify the request in the closure.
var manager = Session.default
manager.request(urlString, method: method, parameters: dict, headers: headers, requestModifier: { $0.timeoutInterval = 120 }).validate().responseJSON { response in
OR
RequestModifiers also work with trailing closure syntax.
var manager = Session.default
manager.request("https://httpbin.org/get") { urlRequest in
urlRequest.timeoutInterval = 60
urlRequest.allowsConstrainedNetworkAccess = false
}
.response(...)
AF.request(url, method: .get).responseDecodable(of: Weather.self) { response in
switch response.result {
case .success(let data):
print(data)
var statusCode = response.response?.statusCode
if statusCode == 200 {
print(response)
}
case .failure(let error):
print(error)
}
}