When API request fails, I need to know number of failed attempts. Backend has added a property ‘attempts’ to error object. How can I find this value, since NSError is not KV pairing compliant and I don’t see it when I log the error object to console.
If you are using NSURLSession for urlrequest , then you will have delegate methods for NSURLSession responses , they are:
->didReceiveResponse = here you receive the response that urlrequest has completed and response received status
->didReceiveData = here you get the SUCCESS response date for your request
->didCompleteWithError = here you get the FAILURE response (i.e) ERROR callback ,this is called every time when request fails , which gives you error data
Related
I have an api (nodejs) which saves my application data in MongoDB. But when I send the request, node throws an error which says that score is undefined
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'score' of undefined
And when Xcode sends the request, the application works for about 30 seconds and then crashes and Xcode logs: "The request timed out."
this is my Swift code:
let parameters = ["score": scoreBoard]
print(parameters)
AF.request("http://localhost:4000/update/score", method: .post, parameters: parameters).responseDecodable(of: [jsonData].self) {response in
let json = JSON(response.data!)[0]["score"]
scoreBoard = json.rawString()!
}
The problem was with Node I didn't use a body parser. When I included a body-parser then it was able to retrieve the data from the body.
I have to make 10 different http post method to server, and I'm doing this asynchronously. but my success of failure response will hit to same method. but if some request fails of time out i want to know which http cal has failed, is this possible to track. And how to get the tag value for the response.
I am confused about this method, specially about the error part and the documentation. Here on the documentation it says that
If the request completes successfully, the data parameter of the
handler block contains the resource data, and the error parameter is
nil. If the request fails, the data parameter is nil and the error
parameter contain information about the failure.
The problem is that, I have seen that some http response error codes fall into the "there is an error" and some dont, furthermore I can have data and error at the same time (but supposedly one should be nil at all times according to the documentation).
[NSURLConnection sendAsynchronousRequest:theRequest
queue:[[NSOperationQueue alloc] init]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
For example, my server sends a 401 response if the user uses wrong credentials, and this is cached inside the error clause, but if i send a 409 (duplicate entry) this is NOT cached by it. Im having some issues redirecting the flow because of this, im not sure what this method will consider an error and what it will not.
Also, how do i properly check for this?, I thought that just checking if there is an error, and then checking what was the code of the response would suffice to display a message or take an action, but as I described before, some "error" codes don't necessarily generate the error object. Should i first check for the status code?
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
int responseStatusCode = [httpResponse statusCode];
if (responseStatusCode == 200)
{
// If 200, assume everything went well?
} else
{
// Something went wrong, check for the code and the error here?
}
From my experience an error occurs when there is no response at all from the server, that's why the data is 0. If a server returns 400 or 500 error then these are a response from your server and depending on your server code maybe an error message you can parse.
I have an iOS app that is using RestKit 0.20.1 to pull data from a server. The server at this time can send JSON formatted data but is not able to receive JSON formatted data.
This is where my problem is. POST requests require HTTP Body and the server is set up to receive XML. I have implemented the RKXMLReaderSerialization add on so I can receive XML but I can't find any current way of sending an XML formatted HTTP Body with RestKit.
This question "Send post request in XML format using RestKit " is what I was looking for but the answer from Imran Raheem is now (as far as I can tell) obsolete due to changes in RestKit.
I am using this method for the POST
[[RKObjectManager sharedManager] postObject:nil path:#"/rest/search?ip=255.255.255.0" parameters:search success:nil failure:nil];
Here is what the RestKit objectManager says about the postObject method
/**
Creates an `RKObjectRequestOperation` with a `POST` request for the given object, and enqueues it to the manager's operation queue.
#param object The object with which to construct the object request operation. If `nil`, then the path must be provided.
#param path The path to be appended to the HTTP client's base URL and used as the request URL. If nil, the request URL will be obtained by consulting the router for a route registered for the given object's class and the `RKRequestMethodPOST` method.
#param parameters The parameters to be reverse merged with the parameterization of the given object and set as the request body.
#param success A block object to be executed when the object request operation finishes successfully. This block has no return value and takes two arguments: the created object request operation and the `RKMappingResult` object created by object mapping the response data of request.
#param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the resonse data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
If I have the MIMEType set to JSON the Trace shows my request.body is being populated like so request.body={"Search":"Trending"}.
However if I set the MIMEType to XML the Trace shows the request.body=(null)
Here is the line I use to change the MIMEType
[RKObjectManager sharedManager].requestSerializationMIMEType = RKMIMETypeJSON;
I am pretty new to iOS and Objective-C so I may be setting up the NSDictionary that is used in the parameters of the `postObject' method wrong. Here it is just in case....
NSArray *objects =[NSArray arrayWithObjects:#"trending", nil];
NSArray *keys =[NSArray arrayWithObjects: #"Search",nil];
NSDictionary *params = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
self.search=params;
Any help would be greatly appreciated! Given that I am new Snippets are especially helpful!
Oh and BTW if anyone can point me to REST method that accepts JSON input I would gladly pass it on to my server guy so I can just avoid XML all together.
As feared and suggested in other posts on this topic writing XML is not supported in version of RestKit 0.20.1. Here is a link to my conversation with Blake Watters on the subject.
https://github.com/RestKit/RestKit/issues/1430#issuecomment-19150316
I never did clear up why the request.body= (null) when the MIMEType is set to XML.
The manager of the server has agreed to set it up to receive JSON. That is how I plan to work around this.
Several times before I used the method...
NSURLResponse *response;
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
to send/receive data synchronously when in an NSOperation and it has worked.
I'm working on a new project (new API, new server) now and the error just isn't being populated.
I'm using Charles proxy to snoop the network traffic and I can see "Response Code 500 Internal Server Error" coming back from the failed request in Charles but in the app the error object is always nil.
Like I said, I've used this loads before and the error is always populated if an error occurs.
Is there something on the server side that I can point out to the server side dev? He's adamant that I must be doing something wrong. The only thing I don't understand is that Charles is picking up response code 500 from it.
N.B. The problem is not that the error is occurring. The problem is that when it does occur the NSError object is not reporting it back to me. Just to clear it up in case anyone tells me to ask the server dev to fix the error. :-)
Your error object is not populated because the request succeeded from NSURLConnection's perspective -- that is, it was able to send data to the server and receive a response.
For protocol-specific errors, you need to inspect the NSURLResponse you get back. In this case, cast the response to NSHTTPURLResponse and invoke -statusCode.
The error is only populated if there is no response from the server or not a valid HTTP response, e.g. connection loss etc.
"Response Code 500 Internal Server Error" means there was an internal server error and your server returns an HTTP message with the response code 500. You should use NSHTTPURLResponse instead of NSURLResponse and call the statusCode method to check the HTTP response code. If the response code starts with 2 everything is fine. So I usually have a check like this: statusCode / 100 == 2.
For more HTTP response codes see http://en.wikipedia.org/w/index.php?title=HTTP_response_codes