Error Code = -1005 randomly, with intermittent internet and Alamofire - ios

In my application when I try to obtain data Alamofire, but present connection problems, randomly presented the error = Optional (Error Domain = NSURLErrorDomain Code = -1005 "The network connection was lost." so responseObject is nil. What is the best way to handle the data so that when it is nil, it’s make the call again?
Attached my call to the server:
makeCall(dirurl, param: parame, completionHandler: { responseObject, error in
print("responseObject = \(responseObject); error = \(error)")
//here should control for the call is generated until it is different from nil
self.datosRequest = responseObject!
self.datosContenido = self.datosRequest["datos"] as! NSDictionary
self.extractData()
self.tableGastosComunes.reloadData()
return
})
func makeCall(dirurl: String, param : [String:NSObject], completionHandler: (NSDictionary?, NSError?) -> ()) {
Alamofire.request(.POST, dirurl, parameters: param, encoding:.URL).responseJSON { response in
switch response.result {
case .Success(let value):
completionHandler(value as? NSDictionary, nil)
case .Failure(let error):
completionHandler(nil, error)
}
}
}

Related

API call using Alamofire sometimes returning connection fail error

I am using alamofire for api calling. The request call is going to success block every time but sometimes with the same request the call is going to failure block with error "The network connection was lost". As there is no problem with network connection, I am not able to find the solution for the particular issue. Here is my code-
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 120
manager.request(url, method: .post, parameters: requestDictionary ?? [:], encoding: JSONEncoding.default).responseJSON(completionHandler: { (response) in
switch response.result {
case .success:
KVNProgress.dismiss()
let jsonString: String = String(data: response.data!, encoding: String.Encoding.utf8)!
print(jsonString)
let dict : [String : Any ] = response.result.value! as! [String : Any]
let msg = dict["Message"] as? String
if msg == "Session id is not valid." {
//logout process…
}, onCancelClick: {
})
}else{
success(response.result.value! as AnyObject)
}
case .failure(let error):
KVNProgress.dismiss()
print("Request failed with error: \(error.localizedDescription)")
failure(“Unexpected error”)
}
})
Thanks in advance. :)
My code is inside block where i have already checked for internet connection-
if(Utilities.checkInternetConnection())
{
// My previous code
}
else
{
connectionFailed(Constant.serverAPI.errorMessages.kNoInternetConnectionMessage)
}
i too had this problem, many time API call return connection fail error.
i solve it it by catching the connection Fail error and recalling the API error one more time from connection fail closure

Alamofire API request is getting failed with responseSerializationFailed in swift 3

I am calling normal API call with Alamofire, And I am not passing any data with that in networking manager class.
My Networking class is
func executeGetRequest(url:String,requestVC:UIViewController,completionHandler:#escaping (_ responseObject:Any?) -> Void!,failureHandler:#escaping (_ connectionError:NSError?) -> Void!){
//Checking internet alert
if !self.isConnectedToInternet(){
// requestVC.showAlert(kText_AppName, message: kText_NoInternet)
return
}
requestVC.showLoader()
Alamofire.request(url).responseJSON {
(response:DataResponse) in
requestVC.removeLoader()
switch(response.result) {
case .success(_):
if response.result.value != nil{
completionHandler (response.result.value)
}
break
case .failure(let error):
failureHandler (error as NSError?)
break
}
}
}
and i am calling it from my main class
kNetworkManager.executeGetRequest(url: kAppAccessTokenURL, requestVC: self, completionHandler: {
(responseObject) -> () in
print("responseObject:\(responseObject!)")
}, failureHandler: {(error)-> () in
print("response object:\(error!)")
self.showAlert(message: (error?.description)!, title: kText_AppName)
if error?._code == NSURLErrorTimedOut {
//timeout here
self.showAlert(message: kText_timeout, title: kText_AppName)
}
})
Its getting always request fail and showing error as responseSerializationFailed
if I call directly in Main Class without manager class like
Alamofire.request(kAppAccessTokenURL).responseString { response in
I am able to getting response, can anyone suggest me where getting wrong in Network class.
Here you
Alamofire.request(kAppAccessTokenURL).responseString
and there
Alamofire.request(url).responseJSON
look to that
let jsonText = "{\"first_name\":\"Sergey\"}"
var dictonary:NSDictionary?
if let data = jsonText.dataUsingEncoding(NSUTF8StringEncoding) {
do {
dictonary = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
if let myDictionary = dictonary
{
print(" First name is: \(myDictionary["first_name"]!)")
}
} catch let error as NSError {
print(error)
}
}

How do I get at the underlying Error from an Alamofire error?

For this request:
Alamofire.request("https://google.com").responseCollection { (response: DataResponse<[User]>) in
guard response.result.isSuccess else {
print(response.error)
return
}
}
I see this printed in the console:
Optional(my_app_name.BackendError.jsonSerialization(Alamofire.AFError.responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error
Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character
0." UserInfo={NSDebugDescription=Invalid value around character 0.}))))
What I've tried:
Alamofire.request("https://google.com").responseCollection { (response: DataResponse<[User]>) in
guard response.result.isSuccess else {
print(response.error)
if let error1 = response.error as? AFError {
print(error1) // Execution DOES NOT reach here.
}
if let error2 = response.error as? BackendError {
print(error2) // Execution DOES reach here.
}
return
}
}
print(error2) above prints:
jsonSerialization(Alamofire.AFError.responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error
Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character
0." UserInfo={NSDebugDescription=Invalid value around character 0.})))
What I'm trying to do is get at the underlying error so I can parse the domain, code, and userInfo properties.
I created the BackendError enum that Alamofire provides as an example at https://github.com/Alamofire/Alamofire#handling-errors :
enum BackendError: Error {
case network(error: Error) // Capture any underlying Error from the URLSession API
case dataSerialization(error: Error)
case jsonSerialization(error: Error)
case xmlSerialization(error: Error)
case objectSerialization(reason: String)
}
and I also implemented the example generic response object serialization exactly like the example at https://github.com/Alamofire/Alamofire#generic-response-object-serialization :
extension DataRequest {
#discardableResult
func responseCollection<T: ResponseCollectionSerializable>(
queue: DispatchQueue? = nil,
completionHandler: #escaping (DataResponse<[T]>) -> Void) -> Self {
let responseSerializer = DataResponseSerializer<[T]> { request, response, data, error in
guard error == nil else {
return .failure(BackendError.network(error: error!))
}
let jsonSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments)
let result = jsonSerializer.serializeResponse(request, response, data, nil)
guard case let .success(jsonObject) = result else {
return .failure(BackendError.jsonSerialization(error: result.error!))
}
guard let response = response else {
let reason = "Response collection could not be serialized due to nil response."
return .failure(BackendError.objectSerialization(reason: reason))
}
return .success(T.collection(from: response, withRepresentation: jsonObject))
}
return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
}
}
I think there are switches, cases, and casts to and from BackendError, AFError, Error, and/or NSError, but I can't seem to get it.
How can I get at the underlying error so I can parse the domain, code, and userInfo properties?
I'm using Swift 3 and Alamofire 4.3.0 .
I know the answer is a little late ;-). But try this:
... } catch let error as NSError {
print("UnderlyingError: \(String(describing: error.userInfo[NSUnderlyingErrorKey]))")}
For Alamofire 4.3, look at response.result:
if case let .failure(error) = response.result {
let error = error as NSError
print("\(error.domain)")
print("\(error.code)")
print("\(error.userInfo)")
}
Try this
let underlyingError = error.errorUserInfo["NSUnderlyingError"] as! NSError
let code = underlyingError.code
let domain = underlyingError.domain
let userInfo = underlyingError.userInfo

Completion handler for Alamofire network fetch

I am attempting to create a function which will return a list of custom objects, created from parsing JSON. I am using AlamoFire to download the content. I have written this function which, on success, creates an array of locations to be returned. However, the returns are always nil. My code is below:
func fetchLocations() -> [Location]? {
var locations : [Location]?
Alamofire.request(.GET, myURL)
.responseJSON { response in
switch response.result {
case .Success(let data):
locations = createMapLocations(data)
case .Failure(let error):
print("Request failed with error: \(error)")
}
}
return locations
}
I am pretty positive the issue is that the functioning is returning before the network request is complete. I am new to Swift, and unsure how to handle this. Any help would be appreciated!
You can read more about closures/ completion handlers https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html or google.
func fetchLocations(completionHandler: (locations: [Location]?, error: NSError) -> ()) -> () {
var locations : [Location]?
Alamofire.request(.GET, myURL)
.responseJSON { response in
switch response.result {
case .Success(let data):
locations = createMapLocations(data)
completionHandler(locations, error: nil)
case .Failure(let error):
print("Request failed with error: \(error)")
completionHandler(locations: nil, error: error)
}
}
}
Usage
fetchLocations(){
data in
if(data.locations != nil){
//do something witht he data
}else{
//Handle error here
print(data.error)
}
}

Swift 2 error, converting to JSON

Ive been having an error with swift 2, its so simple but i cant get it
Here's the code before I started updating it for Swift 2:
func updateWeatherInfo(latitude: CLLocationDegrees, longitude: CLLocationDegrees) {
let url = "http://api.openweathermap.org/data/2.5/forecast"
let params = ["lat":latitude, "lon":longitude]
println(params)
Alamofire.request(.GET, url, parameters: params)
.responseJSON { (request, response, json, error) in
if(error != nil) {
println("Error: \(error)")
println(request)
println(response)
self.loading.text = "Internet appears down!"
}
else {
println("Success: \(url)")
println(request)
var json = JSON(json!)
self.updateUISuccess(json)
}
}
}
here's the line throwing error:
let json = JSON(json)
Here's the whole func after i started
func updateWeatherInfo(latitude: CLLocationDegrees, longitude: CLLocationDegrees) {
let url = "http://api.openweathermap.org/data/2.5/forecast"
let params = ["lat":latitude, "lon":longitude]
print(params)
Alamofire.request(.GET, url, parameters: params)
.responseJSON { (request, response, json) in
print("Success: \(url)")
print(request)
let json = JSON(json)
self.updateUISuccess(json!)
}
}
updateUISuccess requires a JSON value, but at the moment I have a (Request )
heres the error description
After a suggestion I tried this:
.Success(let data):
let data_ar = data as! JSON // or NSDictionary or NSString
self.updateUISuccess(data_ar)
case .Failure(let data, let error):
print("Request failed with error: \(error)")
}
but the app crashes at let data_ar = data as! JSON // or NSDictionary or NSString
The variable json looks like an enum value. Try this:
switch json {
case .Success(let data):
let data_ar = data as! NSArray // or NSDictionary or NSString
case .Failure(let data, let error):
print("Request failed with error: \(error)")
}

Resources