ObjectMapper failed to serialize response error Code=2 - ios

Im getting an error while hitting Alamofire get request using Alamofire Object mapper
this is how i'm hitting the API-
APIService.shared.getSlots{ (success,weekSlots, error) in
if success {
self.weekSlots = weekSlots!
print("success!!")
} else {
print(error?.errorMessage ?? "NOPE")
}
}
while getSlot function inside APIService class is-
open func getSlots(completion: #escaping (Bool, [WeekSlot]?, APIError?) -> ()) {
sessionManager.request(APIRouter.getSlots())
.validate(statusCode: 200..<300)
.responseArray(queue: nil,
keyPath: "week_slots",
context: nil) { (response: DataResponse<[WeekSlot]>) in
switch response.result {
case .success(let value):
self.saveArraysToRealm(value: value)
completion(true,value, nil)
case .failure:
let error = self.processFailure(json: JSON(response.data as Any))
completion(false, nil, error)
print(error)
}
}
}
this is my Data model :
import Foundation
import ObjectMapper
import RealmSwift
class WeekSlot: Object, Mappable {
dynamic var date : String? = ""
var slot = List<Slots>()
//Impl. of Mappable protocol
required convenience init?(map: Map) {
self.init()
}
func mapping(map: Map) {
date <- map["date"]
slot <- (map["slots"], ArrayTransform<Slots>())
}
}
Ive declared the request to perform get request and the url is also correct. The API does not accept any parameters except auth token which is handled by sessionManager. However, im getting the following error in response while debugging-
[Request]: GET http://beta.xamidea.in/api/v1/teachers/get_slots/
[Response]: <NSHTTPURLResponse: 0x600000434c80> { URL: http://beta.xamidea.in/api/v1/teachers/get_slots/ } { status code: 200, headers {
Allow = "GET, POST, HEAD, OPTIONS";
Connection = "keep-alive";
"Content-Length" = 477;
"Content-Type" = "application/json";
Date = "Tue, 10 Oct 2017 11:01:53 GMT";
Server = "nginx/1.10.3 (Ubuntu)";
Vary = Accept;
"X-Frame-Options" = SAMEORIGIN;
} }
[Data]: 477 bytes
[Result]: FAILURE: Error Domain=com.alamofireobjectmapper.error Code=2 "ObjectMapper failed to serialize response." UserInfo=. {NSLocalizedFailureReason=ObjectMapper failed to serialize response.}
[Timeline]: Timeline: { "Request Start Time": 529326113.851, "Initial Response Time": 529326113.985, "Request Completed Time": 529326113.986, "Serialization Completed Time": 529326113.987, "Latency": 0.134 secs, "Request Duration": 0.135 secs, "Serialization Duration": 0.001 secs, "Total Duration": 0.136 secs }
▿ request : Optional<URLRequest>
▿ some : http://beta.xamidea.in/api/v1/teachers/get_slots/
▿ url : Optional<URL>
▿ some : http://beta.xamidea.in/api/v1/teachers/get_slots/
- cachePolicy : 0
- timeoutInterval : 60.0
- mainDocumentURL : nil
- networkServiceType : __ObjC.NSURLRequest.NetworkServiceType
- allowsCellularAccess : true
▿ httpMethod : Optional<String>
- some : "GET"
▿ allHTTPHeaderFields : Optional<Dictionary<String, String>>
▿ some : 1 element
▿ 0 : 2 elements
- key : "Authorization"
- value : "Token 4d7ebe501bcd7c910cf1950ab53bc8aa2a4a569d"
- httpBody : nil
- httpBodyStream : nil
- httpShouldHandleCookies : true
- httpShouldUsePipelining : false
▿ response : Optional<NSHTTPURLResponse>
▿ data : Optional<Data>
▿ some : 477 bytes
- count : 477
▿ pointer : 0x00007f896a48aa80
- pointerValue : 140228170394240
▿ result : FAILURE: Error Domain=com.alamofireobjectmapper.error Code=2 "ObjectMapper failed to serialize response." UserInfo= {NSLocalizedFailureReason=ObjectMapper failed to serialize response.}
▿ timeline : Timeline: { "Request Start Time": 529326113.851, "Initial Response Time": 529326113.985, "Request Completed Time": 529326113.986, "Serialization Completed Time": 529326113.987, "Latency": 0.134 secs, "Request Duration": 0.135 secs, "Serialization Duration": 0.001 secs, "Total Duration": 0.136 secs }
- requestStartTime : 529326113.85062999
- initialResponseTime : 529326113.98505801
- requestCompletedTime : 529326113.98612601
- serializationCompletedTime : 529326113.986781
- latency : 0.13442802429199219
- requestDuration : 0.13549602031707764
- serializationDuration : 0.00065499544143676758
- totalDuration : 0.1361510157585144
▿ _metrics : Optional<AnyObject>
What does this error means??
the response from API on success is this-
{
"result": {
"week_slots": [
{
"date": "2017-10-10",
"slots": []
},
{
"date": "2017-10-11",
"slots": [
{
"start": "2017-10-11T20:00:00Z",
"end": "2017-10-11T21:00:00Z",
"availability": true,
"booked": false
},
{
"start": "2017-10-11T10:00:00Z",
"end": "2017-10-11T12:00:00Z",
"availability": true,
"booked": false
}
]
},
{
"date": "2017-10-12",
"slots": []
},
{
"date": "2017-10-13",
"slots": []
},
{
"date": "2017-10-14",
"slots": []
},
{
"date": "2017-10-15",
"slots": []
},
{
"date": "2017-10-16",
"slots": []
}
]
},
"success": true,
"error": {}
}

I found the solution after 1 day, the problem was in keyPath to access "week_slots" , since I was using swiftyjson the correct way to accesss was:
keyPath: "result.week_slots"
So basically whenever you get this error even when the responce from is is success, its because you are unable to map the response in your model correctly

try changing the model class as:
class WeekSlot: Object, Mappable {
dynamic var date : String? = ""
var slot: [Slots] = []
//Impl. of Mappable protocol
required convenience init?(map: Map) {
self.init()
}
func mapping(map: Map) {
date <- map["date"]
slot <- map["slots"]
}
}
also check your slot model

Related

Sending page no in URL request issue. Getting success but empty result

My Api is having Constants.getliked = "get-liked-story?page=1" at it's tail. I am requesting via alamofire but not getting the response. How can I send page number which includes ? and = sign.
let url : String = Constants.wevlrBaseUrl + Constants.privateLink + Constants.getliked
//let sv = UIViewController.displaySpinner(onView: view)
let userToken = UserDefaultValues.authToken
let headers: HTTPHeaders = ["Authorization": "Bearer " + userToken!]
let parameters: Parameters = [
"page": "1" ]
Alamofire.request(url, method: .get, parameters: parameters,headers:headers).responseJSON { response in
print("request-",response.request!)
print("response-",response.response!)
print("data-",response.data!)
print("result-",response.result)
debugPrint(response)
if let JSON = response.result.value {
print("json: \(JSON)")
}
}
output:
[Request]: GET http://169.65.125.111/abcd/public/api/v1/get-liked-story?page=1
[Response]: { URL: http://169.65.125.111/abcd/public/api/v1/get-liked-story?page=1 }
{
Status Code: 200, Headers
{
"Cache-Control" = (
"no-store, no-cache, must-revalidate"
);
Connection = (
"Keep-Alive"
);
"Content-Length" = (
2
);
"Content-Type" = (
"application/json"
);
Date = (
"Mon, 07 Oct 2019 11:37:43 GMT"
);
Expires = (
"Thu, 19 Nov 1981 08:52:00 GMT"
);
"Keep-Alive" = (
"timeout=5, max=99"
);
Pragma = (
"no-cache"
);
Server = (
"Apache/2.4.18 (Ubuntu)"
);
} }
[Data]: 2 bytes
[Result]: SUCCESS: (
)
[Timeline]: Timeline: { "Request Start Time": 592141063.093, "Initial Response Time": 592141063.178, "Request Completed Time": 592141063.178, "Serialization Completed Time": 592141063.178, "Latency": 0.086 secs, "Request Duration": 0.086 secs, "Serialization Duration": 0.000 secs, "Total Duration": 0.086 secs }
json: (
)
Suppose this value for the variables in Constants
let wevlrBaseUrl = "https://stackoverflow.com"
let privateLink = "/questions"
let getliked = "/get-liked-story?page=1"
then use Alamofire request method with url and headers parameters only

Get Response using Alamofire

I am using Alamofire to make Get Response but unable to get the Valid Response . I am using below details . I dono where i am making mistake.
let myID = MEGHA-WORK SE-107
let headers = ["Authorization": "Basic \(base64Credentials)" , "ID": (myID).trimmingCharacters(in: .whitespaces) ]
let parameters:Parameters = ["ID": (myID).trimmingCharacters(in: .whitespaces)]
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 60
manager.request(url, method: .get, parameters: parameters, encoding: URLEncoding.queryString , headers: headers).responseJSON { (response) in
debugPrint(response)
if response.response?.statusCode == 200 || response.response?.statusCode == 201 {
if let value = response.result.value {
let json = JSON(value)
print(json)
completion(json, nil)
}
}
Task <343CF648-7C9A-4E03-9A82-A88BC41EA926>.<6> finished with error - code: -1005
Response
[Request]: GET https://my-services.myservices.com:443/prweb/api/v1/cases?ID=MEGHA-WORK%20SE-107
[Response]: nil
[Data]: 0 bytes
[Result]: FAILURE: Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={NSUnderlyingError=0x109ce9500 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x10d53db00 [0x1b271c310]>{length = 16, capacity = 16, bytes = 0x100201bba06d196d0000000000000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=https://my-services.myservices.com:443/prweb/api/v1/cases?ID=MEGHA-WORK%20SE-107, NSErrorFailingURLKey=https://my-services.myservices.com:443/prweb/api/v1/cases?ID=MEGHA-WORK%20SE-107, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-4, NSLocalizedDescription=The network connection was lost.}
[Timeline]: Timeline: { "Request Start Time": 553592494.567, "Initial Response Time": 553592497.615, "Request Completed Time": 553592497.615, "Serialization Completed Time": 553592497.616, "Latency": 3.049 secs, "Request Duration": 3.049 secs, "Serialization Duration": 0.000 secs, "Total Duration": 3.049 secs }
It seems that the reason is already printed there:
Code=-1005 "The network connection was lost."
Restarting the simulator and erasing all content and settings seems to fix this for others (Simulator->Hardware->Erase All Content and Settings...)
Please check this thread.
You can handle this way :
if (responseJson.response?.statusCode)! > 200 && (responseJson.response?.statusCode)! < 300{
// handle as appropriate because the response will be success
} else {
}
It may helps you to handle the crash. Thank you

convert alamofire json response to variable

I have a question that I already asked several times on stackoverflow and I have tried all of them, there is none of them worked. So I would love to summarize the question for another time, and try to describe it more precise.
I am building an app sending a picture to a python back end for the result of image recognition in xcode swift.
And I am using Alamofire to upload,
here is the uploading part:
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imageData!, withName: "pic", fileName: "filename.png", mimeType: "image/png")
}, to: "http:123456.com/image",
method: .post,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseString { response in
debugPrint(response)
}
case .failure(let encodingError):
print(encodingError)
}
And here is the json response I got from the server end:
[Response]: <NSHTTPURLResponse: 0x600000237de0> { URL: 1234/image } { Status Code: 200, Headers {
"Content-Length" = (
348
);
"Content-Type" = (
"text/html; charset=utf-8"
);
Date = (
"Mon, 09 Apr 2018 20:59:30 GMT"
);
Server = (
"Werkzeug/0.12.2 Python/2.7.12"
);
} }
[Data]: 348 bytes
[Result]: SUCCESS: {
"prediction": [
{
"name": "marshmallow",
"value": 0.2800232470035553
},
{
"name": "caesar salad",
"value": 0.090629942715168
},
{
"name": "egg",
"value": 0.07480788230895996
},
{
"name": "apple",
"value": 0.049235329031944275
},
{
"name": "chickpea",
"value": 0.04692944884300232
}
]
}
[Timeline]: Timeline: { "Request Start Time": 545000363.584, "Initial Response Time": 545000363.642, "Request Completed Time": 545000370.462, "Serialization Completed Time": 545000370.487, "Latency": 0.058 secs, "Request Duration": 6.879 secs, "Serialization Duration": 0.025 secs, "Total Duration": 6.903 secs }
So, the purpose I want to have, is just print the name of the first prediction's name.
like the output is
outcome is marshmallow with a value of 0.28
I have tried several ways:
First, I want to have a struct to store the name as string, value as double, and use a loop to parse it. But whatever I tried, I always get a "null" as output, or nothing.
Any suggestions on this? Thanks in advance.
try this:
upload.responseJSON { response in
if let result = response.result.value {
let json = result as! [String: Any]
if let predictionArray = json["prediction"] as? [[String: Any]],
let firstPrediction = predictionArray.first {
print(firstPrediction)
}
print(json)
}
}

The data couldn’t be read because it isn’t in the correct format returned when getting google contacts

I am trying to retrieve goole contacts in my swift app and I am getting the error below. The user is successfully singing in.
func getUserContacts(email : String){
let urlString = "http://www.google.com/m8/feeds/contacts/\(email)/full"
Alamofire.request(urlString, method: .get)
.responseJSON { response in
switch response.result {
case .success(let JSON):
print(JSON as! NSDictionary)
case .failure(let error):
print(error.localizedDescription)
}
}
}
(lldb) po "http://www.google.com/m8/feeds/contacts/(email)/full"
"http://www.google.com/m8/feeds/contacts/emailhere#gmail.com/full"
(lldb) po error.localizedDescription
"JSON could not be serialized because of error:\nThe data couldn’t be read because it isn’t in the correct format."
(lldb) po response
▿ [Request]: GET http://www.google.com/m8/feeds/contacts/emailhere.com/full
[Response]: <NSHTTPURLResponse: 0x170033da0> { URL: http://www.google.com/m8/feeds/contacts/emailhere.com/full } { status code: 401, headers {
"Cache-Control" = "private, max-age=0";
"Content-Encoding" = gzip;
"Content-Length" = 8761;
"Content-Type" = "text/html; charset=utf-8";
Date = "Thu, 23 Feb 2017 14:19:11 GMT";
Expires = "Thu, 23 Feb 2017 14:19:11 GMT";
Server = GSE;
"X-Content-Type-Options" = nosniff;
"X-Frame-Options" = SAMEORIGIN;
"X-XSS-Protection" = "1; mode=block";
} }
[Data]: 11875 bytes
[Result]: FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
[Timeline]: Timeline: { "Request Start Time": 509552351.480, "Initial Response Time": 509552351.663, "Request Completed Time": 509552351.665, "Serialization Completed Time": 509552351.667, "Latency": 0.183 secs, "Request Duration": 0.185 secs, "Serialization Duration": 0.002 secs, "Total Duration": 0.187 secs }
▿ request : Optional<URLRequest>
▿ some : http://www.google.com/m8/feeds/contacts/emailhere.com/full
▿ url : Optional<URL>
▿ some : http://www.google.com/m8/feeds/contacts/emailhere.com/full
- cachePolicy : 0
- timeoutInterval : 60.0
- mainDocumentURL : nil
- networkServiceType : __ObjC.NSURLRequest.NetworkServiceType
- allowsCellularAccess : true
▿ httpMethod : Optional<String>
- some : "GET"
▿ allHTTPHeaderFields : Optional<Dictionary<String, String>>
- some : 0 elements
- httpBody : nil
- httpBodyStream : nil
- httpShouldHandleCookies : true
- httpShouldUsePipelining : false
▿ response : Optional<NSHTTPURLResponse>
▿ data : Optional<Data>
▿ some : 11875 bytes
- count : 11875
▿ pointer : 0x0000000104e24000
- pointerValue : 4376903680
▿ result : FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
▿ failure : AFError
▿ responseSerializationFailed : ResponseSerializationFailureReason
▿ timeline : Timeline: { "Request Start Time": 509552351.480, "Initial Response Time": 509552351.663, "Request Completed Time": 509552351.665, "Serialization Completed Time": 509552351.667, "Latency": 0.183 secs, "Request Duration": 0.185 secs, "Serialization Duration": 0.002 secs, "Total Duration": 0.187 secs }
- requestStartTime : 509552351.480039
- initialResponseTime : 509552351.66287899
- requestCompletedTime : 509552351.66534299
- serializationCompletedTime : 509552351.66746801
- latency : 0.18283998966217041
- requestDuration : 0.18530398607254028
- serializationDuration : 0.0021250247955322266
- totalDuration : 0.18742901086807251
▿ _metrics : Optional<AnyObject>
my problem was a permissions problem. I added GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/contacts.readonly") and gave my app access in https://myaccount.google.com/security
then this worked:
let urlString = "https://www.google.com/m8/feeds/contacts/default/full?access_token=\(GIDSignIn.sharedInstance().currentUser.authentication.accessToken!)&max-results=\(999)&alt=json&v=3.0"
Alamofire.request(urlString, method: .get)
.validate(contentType: ["application/json"])
.responseJSON { response in
switch response.result {
case .success(let JSON):
var json = JSON as! NSDictionary
print(JSON as! NSDictionary)
case .failure(let error):
print(error.localizedDescription)
}
}

Alamofire: NSLocalizedFailure error (status code 403)

I am trying to retrieve the various user ids from task api, perform a loop on them and POST the array of values to submitScore api.
Desired workflow:
User taps on table cell -> app gets the cell id and display items related to that cell -> user presses a button -> app gets stores data in the form of an array and POSTS to an submitScore api
I can retrieve the various user data with a GET request from task api but I don't know how to:
associate my retrieved ids with the cell id
store the retrieved data (user ids and score) in an array and POST it to my submitScore api in the form below
Array form for POST body:
{ "ratings": [{
"safety_rating_id": 105,
"schedule_job_id": 18,
"score": 9,
"submission_id": 27
},
{
"safety_rating_id": 105,
"schedule_job_id": 18,
"score": 9,
"submission_id": 27
}]
}
Which is why I get thrown this error:
Request failed with error: Error Domain=com.alamofire.error Code=-6003 "Response status code was unacceptable: 403" UserInfo={NSLocalizedFailureReason=Response status code was unacceptable: 403}
Code for POST:
func getTaskDetails(onCompletion: () -> (), onError: ((NSError) -> ())? = nil) {
guard let endPoint = Data.sharedInstance.submitScoreEndpoint
else { print("Empty endpoint"); return }
let user = Users()
let Auth_header = [
"Authorization" : user.token,
]
let parameters = [
"ratings" : [
[
"safety_rating_id" : 106,
"schedule_job_id" : 18,
"score" : 10,
"submission_id" : 27
],
[
"safety_rating_id" : 105,
"schedule_job_id" : 18,
"score" : 9,
"submission_id" : 27
]
]
]
Alamofire.request(.POST, endPoint, headers: Auth_header, parameters: parameters)
.validate()
.responseData {
response in
switch response.result {
case .Success(let data):
let json = JSON(data)
print(json)
onCompletion()
case .Failure(let error):
print("Request failed with error: \(error)")
onError?(error)
}
}
}

Resources