"The network connection was lost" when loading a specific Resource - objective-c

since a few days I have problems with RestKit 0.20
RestKit is included via CocoaPods so it is up to date. I am developing an app for iOS7 and this problems happen on all real and simulated devices.
When I am loading a resource like an image or a pdf file like this:
RKObjectManager *objectManager = [self.restManager objectManager];
[objectManager setAcceptHeaderWithMIMEType:#"image/jpeg"];
[[objectManager HTTPClient] getPath:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (completeBlock) {
UIImage *image = [UIImage imageWithData:responseObject];
completeBlock(image);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failBlock) {
failBlock(error);
}
}];
I get this error message:
T restkit.network:RKObjectRequestOperation.m:148 GET 'https://***/attachment/11787':
request.headers={
Accept = "*";
"Accept-Language" = "en-US";
Authorization = "***";
"User-Agent" = "***";
}
request.body=(null)
E restkit.network:RKObjectRequestOperation.m:174 GET 'https://***/attachment/11787' (200 OK) [1.0048 s]:
error=Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo=0xf7ba400 {NSErrorFailingURLStringKey=https:/***/attachment/11787, NSErrorFailingURLKey=https://***/attachment/11787, NSLocalizedDescription=The network connection was lost., NSUnderlyingError=0x1605c930 "The network connection was lost."}
response.body=(null)
But this is not the common case for all resources but for only a few. The other resources get loaded at the same time (The requests were added to the queue at the same time).
Once this error happends for a resource, the resource will never get loaded again but failing with the same error message.
I cleaned the cache and deleted the app, so it shouldn't be a problem with caching or something like that. And there is no difference if http or https is used.
Similar to this question (without solution): Restkit not work on iOS 7
Do you have any ideas, what I am doing wrong or what causes this behaviour?

Related

Error with RestKit putObject with 204 response Xcode

Im developing a iOS RESTFul client App but I´m in trouble with the 204 response for a PUT request, this is my code:
[objectManager putObject:dataObject path:path
parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSLog(#"Register Success");
completionBlock(YES);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"Register Failed %#", error);
completionBlock(NO);
}];
Everything works, but I´m getting the following error:
E restkit.network:RKResponseMapperOperation.m:320 Failed to parse response data: Loaded an unprocessable response (204) with content type 'text/plain'
NSUnderlyingError=0x16ec4b60 "Cannot deserialize data: No serialization registered for MIME Type 'text/plain'", NSLocalizedDescription=Loaded an unprocessable response (204) with content type 'text/plain'}
response.body=No Content
I´m using pod 'RestKit', '~> 0.23.0'
I hope somebody knows how can I solve that
Thanks in advance!!!
The simplest option is to tell RestKit to treat the text mime type as JSON:
[RKMIMETypeSerialization registerClass:[RKNSJSONSerialization class] forMIMEType:#"text/plain"];
Alternatively, use RKMapperOperation to serialise your object to be sent (or use the object manager to create the request to send) and then pass it on to the HTTP client (or enqueue an operation with the object manager). Check the RestKit github page for examples.

iOS special characters in url

I try to make an api call:
api.app.com/foo/search/Öhm
where Öhm is the search term. The problem is that this url causes a bad url exception, while normal chars work well. I tried with
[searchText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
However this produces a lot of % signs. The api expects Öhm. Any solution for this problem? I am using restkit.
The full error:
Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x16e719d0
{NSUnderlyingError=0x16d70d10 "bad URL", NSLocalizedDescription=bad
URL} 2014-04-03 18:26:55.404 My App[6844:3807] E
restkit.network:RKObjectRequestOperation.m:243 GET '(null)' (0 / 0
objects) [request=0.0084s mapping=0.0000s total=0.0769s]: Error
Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x16e719d0
{NSUnderlyingError=0x16d70d10 "bad URL", NSLocalizedDescription=bad
URL}
The termin is (null) instead of Öhm.
Code:
[[ApiSearchManager sharedManager] search:^(NSArray *result){
//handle success
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
//handle fail - it fails for Öhm
} query:searchTerm];
and on the lower level:
- (void) search:(void (^)(NSArray *))success failure:(void (^)(RKObjectRequestOperation *, NSError *))failure query:(NSString *)query{
[self getObjectsAtPath:[NSString stringWithFormat:#"foo/search/%#", query] parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
if (success) {
success(mappingResult.array);
}
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
if (failure) {
failure(operation, error);
}
}];
}
The % signs are escaping, and that is how the URL should be transmitted. At the server side, the URL gets interpreted (unescaped) and the server-side code will see the special characters as you intended. For example it's very common to see URL's with %20 in them. ASCII character 20 (hex) is a space, so server-side code that obtains the URL (appropriately decoded) see a space in there.
This section of the log:
GET '(null)' (0 / 0 objects) [request=0.0084s mapping=0.0000s total=0.0769s]:
Means you're doing a GET, that the request URL is nil (which would be bad), so status code was obtained because no request was actually sent, it took a little time, blah blah
So, The URL loading system couldn't create a valid URL with which to make your request.
I'm going to guess that the only way you can achieve this is to not have a properly configured baseURL in your RKObjectManager. Check that. (though I would expect that to fail earlier - so you may be reduced to debugging around RKObjectRequestOperation.m, line 243, and back up the call stack)

Intermittent server error in iOS7

I am using NSURLSessionDownloadTask to pull down a simple text file from my goDaddy server using the following code:
-(void)getTheInternetFile
//Fire up the downloadTask to pull the file down from my web server.
NSURLSessionDownloadTask *getTheFile = [session downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.myserver.com/utility/file.txt"]]
completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error)
{
if(error)
{
NSLog(#"Can't do what I want as we have an error %#", [error localizedDescription]);
}
else
{
NSLog(#"It worked");
}
}];
[getTheInternetFile resume];
}
The problem I am having is that this works really well...sometimes. Other times I get an error message that states: "A server with the specified hostname could not be found".
As the URL is hard coded and never changes, I am at a loss to how this can even happen. Unless goDaddy is letting me down, and the server has all of a sudden become unavailable part of the time, I am at a loss. For what it's worth this just started acting this way today, so maybe it is goDaddy.
So it turns out it was goDaddy's server having issues, despite their website reporting that there were none. It took 15 minutes on hold to find out that my code is fine.

AFNetworking Half the time downloading half the data

I'm trying to download a small file, about 5.5kb.
Half of the time it only downloads half of the json, and then of course fails parsing that data. The other half of the time everything works completely normal.
I have a good internet connection.
Im using AFNetworking 2.0. I got it off of the main branch today (1/16/2014).
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:[NSString stringWithFormat:#"%#Physicians/Types/?os=1",BaseUrl] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
NSLog(#"Error: %#", operation.responseString);
}];
Here is the exact error, but i already know its a parsing error:
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (No string key for value in object around character 4480.) UserInfo=0x15ecd010 {NSDebugDescription=No string key for value in object around character 4480.}
This is the sample from their website. And like I said it works half of the time.
Do I need to set some sort of chunk size? Is it because their Github page says the current build is failing?
Interestingly enough, it seems to always fail at the exact same point in the file. I can tell this because in the error, I output the response string.
I am not able to reproduce this in any browser, or in my old app which used asihttprequest
***Update 1/28/2014
I downloaded the current version today, which is passing build, and it still fails. When I save out to disk what it does receive it's 5,391 bytes. Again, it fails at the same point each time. In the middle of the work dentist. There aren't any weird characters there.

AFNetwork 2.0 POST results in a 403 error

I'm using AFNetworking 2 to perform a simple post operation:
[self.manager POST:#"person"
parameters:(NSDictionary *)parameters
constructingBodyWithBlock:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success)
success(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure)
failure(error);
}];
Every time this runs, XCode's console says that I got "Request failed: forbidden (403)" as the response. If I run against the exact same url shown in the NSErrorFailingURLKey via curl, I immediately get back the results I'd expect from the POST operation.
I haven't enabled any type of authentication on the script being called. It's just a Restler class. Am I missing a step here?
Adding the 'constructingBodyWithBlock' changed the type of message being sent. Had to remove that in order to make it work.