Display user friendly message for json serialisation error - ios

Iam working on an ios application which uses Alamofire for networking. Some times i get json serialization error. I need to display some user friendly messsage when this error comes. How can I do this by checking Nserror code.
Any help will be appreciated.

If your response gives serialization error then you can get status isFailure You can display some custom message or can user response.result.error object.
Alamofire.request(url, method: .post, parameters: param, encoding: URLEncoding.httpBody, headers: nil).responseSwiftyJSON { (response) in
if response.result.isSuccess {
// Handle your json
} else {
// display message Something went Wrong
}
}

You can actually check AFError.swift file to get familiar with possible values.
switch responseJson.result.error as? AFError{
case .responseSerializationFailed(let reason)?:
switch reason {
case .inputDataNil:
break
case .inputDataNilOrZeroLength:
break
case .inputFileNil:
break
case .inputFileReadFailed(let at):
break
case .stringSerializationFailed(let encoding):
break
case .jsonSerializationFailed(let error): break
***////// DO What ever you want here //////////////////***
case .propertyListSerializationFailed(let error):
break
}
case .some(.multipartEncodingFailed(let reason)):
break
case .some(.responseValidationFailed(let reason)):
break
case .some(.responseSerializationFailed(let reason)):
break
case .none:
<#code#>
case .some(.invalidURL(let url)):
<#code#>
}

Related

Handling errors properly in swift

I am trying to learn swift and I have hit a wall... I want to be able to switch the type of error i get back so I can do different things. It works fine in the .success but not in the .failure
exporter.export(progressHandler: { (progress) in
print(progress)
}, completionHandler: { result in
switch result {
case .success(let status):
switch status {
case .completed:
break
default:
break
}
break
case .failure(let error):
// I want to check what the error is
// e.g. the debugger says its "cancelled"
break
}
})
}
Can somebody help me with this?
Thanks
If you just want to see what happened, print the error object's localizedDescription.
print(error.localizedDescription)
If you have a decision to make, cast to NSError and examine the domain and code. That is more reliable though not as user-friendly. Only actual testing will tell you what the possible values are.
let error = error as NSError
if error.domain == ... && error.code == ... {
You can work out the corresponding Swift Error type by looking in the FoundationErrors.h header file. Once you do, you can refine your case structure to filter the error type into its own case:
case .failure(let error as NextLevelSessionExporterError):
// do something
case .failure(let error):
// do something else

Alamofire - responseSerializationFailed

I really need help with this one. I'm trying to do POST request using Alamofire, but for some reason I'm always getting an error from the title. When I test in POSTMAN, I'm getting okay response. Here is screenshot from POSTMAN, just to get things clearer:
And this is how I'm calling this API in code:
let parameters: Parameters = [
"data": [
"action":"homeimages"
]
]
print("Params: \(parameters)")
Alamofire.request(Constants.API_URL_2, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON {
response in
print("Response: \(response)")
switch response.result {
case .success(let value):
print("Response: \(value)")
break
case .failure(let error):
print(error)
}
}
As far as I know responseserializationfailed error, mostly error with API itself however as you stated, you are getting response in POSTMAN please check below things :
URL(check small/caps well), parameters are correct(check caps and dictionary format as well)
Sometimes we don't need below (optional) parameter , delete this parameter and check
encoding: JSONEncoding.default

How to describe error from Alamofire using switch case in Swift?

I want to give info to the user about the error that occurred while sending a request to the server. I use Alamofire.
The code is like below:
Alamofire.request(url, method: methodUsed, parameters: parameters).responseData { (response) in
switch response.result {
case .failure(let error) :
// I want to the describe the error in here
case .success(let value) :
let json = JSON(value)
completion(.success(json))
}
}
I have tried but I can't switch the error. I want something similar to this to be placed in the code above:
switch error {
case .NoSignal : // give alert to the user about the signal
case .ServerError : // give alert to the user about server error
}
For some case I want to inform the user to take some action on the alert but I don't know what the available cases are and I don't know the syntax that has to be used.
As per Jayesh Thanki says you can identify the server error using status code and for internet connectivity you can use NetworkReachabilityManager of Alamofire. Write following code in viewDidLoad():
var networkManager: NetworkReachabilityManager = NetworkReachabilityManager()!
networkManager.startListening()
networkManager.listener = { (status) -> Void in
if status == NetworkReachabilityManager.NetworkReachabilityStatus.notReachable {
print("No internet available")
}else{
print("Internet available")
}
You can identify error using status code. response.response.statusCode.
There is lots of HTTP status code and using them you can inform end user with alert.
Here is wikipedia link for list of status code.
For example is status code is 200 OK then its successful HTTP request
and status code is 500 Internal Server Error then its server related error.
You can also provide error description using response.result.error.localizedDescription if error is available.

How can I access Success/Failure cases from this struct?

Using Alamofire v4.0, Alamofire.upload() using MultipartFormData has changed, but I can't find out how to get the success/error case with the enumeration returned in the closure (type is SessionManager.MultipartFormDataEncodingResult)
Looking into the SessionManager.MultipartFormDataEncodingResult struct, here is what I get:
public enum MultipartFormDataEncodingResult {
case success(request: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?)
case failure(Error)
}
So Xcode seems to have been super unhelpful here and autocompleted the initialiser for that enum rather than the case statement. You would want to do something similar to what you have for the .failure case:
switch encodingResult {
case .success(let request, let streamingFromDisk, let streamFileURL):
// you can now access request, streamingFromDisk and streamFileURL in this scope
...
case .failure(let errorType):
// you can now access errorType in this scope
...
}

409 is success in Alamofire?

Strange thing happened to me while implementing networking based on Alamofire. So, my backend can return me 409 and when I get it I want to react properly, so I went for a regular solution:
Alamofire.request(someRequest).responseJSON { response in
switch response.result {
case .Success(let value):
// I get 409 here...
if response.response?.statusCode == 409 {
// ...
}
case .Failure(let error):
// While it should be here...
}
}
Why is it happening? Is it some sort of backend issue or what? I can only thing of one explanation: Request completed, so it's .Success even though you got 409, but this explanation doesn't convince me 😅
HTTP 4.xx class of status codes are intended for situations in which the client seems to have erred, so in normal cases you are to show some kind of error message to the user when it was generated by the server.
In Alamofire world, you can tap into .validate() method if you want response to generate an error if it had an unacceptable status code:
Alamofire.request(someRequest)
.validate(statusCode: 200..<300)
.responseJSON { response in
switch response.result {
case .Success(let value):
...
case .Failure(let error):
// You'll handle HTTP 409 error here...
}
}

Resources