Image upload time out error in ios - ios

I use the below code to upload image to server.
NSString *url = [NSString stringWithFormat:#"http://192.250.1.52:xxx/api/user/profileUploadUser?userid=27&emailid=tom#gnts.in"];
NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc]init];
[jsonDict setObject:ImageToUpload forKey:#"file"];
////////ImageToUpload = /var/mobile/Containers/Data/Application/89112E0B-C1D6-4408-8586-6C5B4A431713/Documents/61.png
[manager POST:url parameters:jsonDict
success:^(AFHTTPRequestOperation *operation, id responseObject)
{ //////success code }
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Image upload" message:#"failure" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
NSLog(#"error message %#",error);
// handle failure
}];
It always enter into the failure block and
shows the error message.
error message : Error Domain=NSURLErrorDomain Code=-1001 "The request
timed out."
UserInfo={NSErrorFailingURLStringKey=http://192.250.1.52:xxxx/api/user/profileUploadUser?userid=27&emailid=tom#gnts.in, _kCFStreamErrorCodeKey=-21022}}}

Check your internet speed might be slow,
[manager.requestSerializer setTimeoutInterval:30];//Set request timeout interval time & interact with backend developer for same.
One more thing you can manage one retry counter in singleton & give second request if fails & if again fails then show toast message internet speed is slow.

You are trying to a POST operation whereas what you want is a file upload.
Try out AFNetworking multipart file upload.

Related

AFHTTPSessionManager or AFHTTPOperationManager been skipped, not even executing

I'm new to IOS development and was doing something related to dynamic data request through a 3rd party api using AFNetworing, I assume this is the good way to do networking in IOS?
One issue I have so far is I have two AFHTTPSessionManager in two different class implementation files. When I ran the application, the first one executes successfully. but the second one is not working and the problem is in debug mode, I can see that the
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:PLACE_DETAIL_URL
parameters:#{ #"key": APPLICATION_KEY,
#"placeid": placeid,
#"extensions": #"review_summary"
}
success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"%#", responseObject);
placeDetail = [[NSDictionary alloc] initWithDictionary: (NSDictionary *) [responseObject objectForKey:#"result"]];
} failure:^(NSURLSessionDataTask *task, NSError *error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Places"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
is not even executing. It's been skipped for some reason. Is this a bug or I can only have on AFHTTPSessionManager or AFHTTPOperationManager at a time?
P.S.
debug gif posted here for clear idea.
thanks for all your help.

AFNetworking get JSON after 404 Bad Request still getting a JSON response

I have a Django Rest Api with a iOS app and right now I'm testing AFNetworking to change the HTTP Request my app is doing but i came with this dilema that i dont know how to handle, first is that on REST Standards when i get an error i should return a 404_BAD_REQUEST as a status if either sends or something wrong happens and this is OK. The issue comes when AFNetworking sees this 404. I still want to see the JSON that it returns.
curl -X POST http://domain.com:8000/user-login/ -d "nick=superUser&pass_field=superPassword"
i get 202 Status HTTP:
{
"nick": "eddwinpaz", "rate": 30, "name": "Eddwin Paz", "avatar": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-prn2/t1.0-1/p160x160/10270540_10154074250190063_1762683854515424400_n.jpg", "id": 9}eddwinpazs-MacBook-Pro:~ eddwinpaz$
}
When i get 404 BAD REQUEST i get:
{"message": "Invalid Username or Password"}
I want to grab that message json tag if i get a 404 Error
I've the following code. and put it on the message on the Alert
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"nick": #"eddwinpaz",#"pass_field":#"eddwinpaz1"};
AFHTTPRequestOperation *operation = [manager POST:#"http://domain.com/user-login/"];
[operation addAcceptableStatusCodes:[NSIndexSet indexSetWithIndex:404]];
[manager POST:#"http://domain.com/user-login/" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Login Failed"
message:#"E-mail or password are wrong, Please Try Again"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[hud hide:YES];
}];
Per default the error code 404 is handled as an error code. You could add it as one of the accepted error codes via
AFHTTPRequestOperation *operation = [manager POST:#"http://doma...
[operation addAcceptableStatusCodes:[NSIndexSet indexSetWithIndex:404]];
Then success: is called on an 404 response and you can handle it there.
The answer by #miho did not work for me. addAcceptableStatusCodes does not exist in AFNetworking 2.5.0 from what I can tell. I had to do the following.
NSMutableIndexSet *acceptedCodes = [[NSMutableIndexSet alloc]
initWithIndexSet:operation.responseSerializer.acceptableStatusCodes];
[acceptedCodes addIndex:304];
operation.responseSerializer.acceptableStatusCodes = [acceptedCodes copy];

AFNetworking 2.0 : Cannot POST with JSON from IOS

Ever since upgrading my IOS code to use AFNetworking version 2.0 instead of 1.x, I cannot do an HTTP Post any more with JSON parameters.
I suspect it is because my HTTP request header is not "application/json" but I have tried to do that and it still does not work.
This is my test code for trying to POST by JSON:
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:
email, #"email",
password, #"password",
nil];
[[OTApiClient sharedInstance] POST:#"login" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"result: %#", responseObject);
Boolean response = [[responseObject valueForKey:#"success"] boolValue];
if(response == TRUE) {
//ok, success
NSLog(#"success");
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Success!" message:#"Successfully logged in" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
} else {
NSLog(#"Not successful");
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Sorry" message:#"The email or password is incorrect." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:self.view animated:YES];
});
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %# , for operation: %#", error, operation);
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Sorry" message:#"There is a problem connecting to the server, please try again soon." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:self.view animated:YES];
});
}];
});
and I keep getting this error :
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0xca80730 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.} , for operation: <AFHTTPRequestOperation: 0xca6bee0, state: isFinished, cancelled: NO request: <NSMutableURLRequest: 0xca76040> { URL: http://1.2.3.4:9000/api/login }, response: <NSHTTPURLResponse: 0xc963d60> { URL: http://1.2.3.4:9000/error404 } { status code: 404, headers {
"Content-Length" = 1809;
"Content-Type" = "text/html; charset=utf-8";
} }>
I am very sure that the server is up and accessible because all other GET calls work properly.
I have checked the updated documentation for AFNetworking 2.0 and it seems like what I have is the right way to do a JSON POST
Please let me know if I missed anything
Thanks
IS
Actually, I finally got it to work.
Basically, for my requestSerializer of the AFHTTPRequestOperationManager, I was using AFHTTPRequestSerializer and then trying to set the Content-Type to "application/json"
But once I switched to using AFJSONRequestSerializer instead, it works fine now
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
operationManagerInstance.requestSerializer = requestSerializer;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[serializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
manager.requestSerializer = serializer;
now it will work.
I encountered the same problem using AFNetworking API through Swift, trying to send a post request and finally got it work as well thanks to user1805458's post.
Basically, for my requestSerializer of the AFHTTPRequestOperationManager, I was also using AFHTTPRequestSerializer and then trying to set the Content-Type to "Application/JSON" and it did not work.
But once I switched to using AFJSONRequestSerializer instead, it works fine now:
let manager = AFHTTPRequestOperationManager()
manager.requestSerializer = AFJSONRequestSerializer(writingOptions: nil)
// Contrary to user1805458's solution, I did not need to use these two instructions below using Swift.
// manager.requestSerializer.setValue("Application/JSON", forHTTPHeaderField:"Content-Type")
// manager.requestSerializer.setValue("Application/JSON", forHTTPHeaderField:"Accept")
I hope it will help you to fix this error in case where you use Swift, AFNetworking and try to send a post request containing a JSON body.

AFNetworking Error Domain Code=-999 ? But works fine?

I'm getting a strage error from AFNetworking even the though the request seems to work fine (as the change actually happens on the site).
Error Domain=NSURLErrorDomain Code=-999 "The operation couldn’t be completed
(NSURLErrorDomain error -999.)" UserInfo=0x1fd4a080
{NSErrorFailingURLKey=http://gcm.greenlightdispatch.com/services/json/}
The strange thing is that it returns this error but it actually doesn't have a problem completing the request (on the server, the information passes through just fine and all).
AFHTTPClient *httpClient = [[[AFHTTPClient alloc] initWithBaseURL:url] autorelease];
[httpClient postPath:#"" parameters:[NSDictionary dictionaryWithDictionary:params]
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", [responseObject objectFromJSONData]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error.description);
}];
Thanks for the help
This has been answered many times before. The operation is being canceled which is why you get that error.
What to do about an NSURLErrorDomain -999?

RestKit 0.20.0 getobject

I am new to restkit.I have integrated restkit 0.20.0-pre6 successfully by following instructions from github. Then I have build my project in console, I got the following
restkit:RKLog.m:34 RestKit logging initialized...
after that I would like to get data at a path
Initially there is an activation screen .so I would like to send activation code to it and if it is correct, I would like to get corresponding details .
NSURL *urll=[NSURL URLWithString:#"http://url/FirstRest/rest/application/Activate"];
AFHTTPClient* client = [[AFHTTPClient alloc] initWithBaseURL:urll];
RKObjectManager *manager = [[RKObjectManager alloc] initWithHTTPClient:client];
[RKObjectManager setSharedManager:manager];
Article *article = [Article new];
article.activationCode = #"S1234";
[manager.router.routeSet addRoute:[RKRoute routeWithClass:[Article class] pathPattern:#"/FirstRest/rest/application/Activate/:activationCode" method:RKRequestMethodGET]];
[[RKObjectManager sharedManager] getObject:article path:nil parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *result)
{
// Request
NSLog(#"result is ************* %#",result);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:[error localizedDescription] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}];
`
in my console I'm getting
I restkit.network:RKHTTPRequestOperation.m:179 GET 'http://url/FirstRest/rest/application/Activate/S1234' (200 OK) [1.4744 s]
2013-01-28 14:07:59.284 Polls[985:15103] E restkit.network:RKResponseMapperOperation.m:240 Failed to parse response data: Loaded an unprocessable response (200) with content type 'application/json'
I couldn't find out what does it really means and how to overcome this
The JSON you are getting as a response is probably malformed.
I've encoutered a similar situation and checked out the actual error object (CMD+SHIFT+F for "Failed to parse response", you'll find the lines).
After print description of the error, I found the JSON I was getting had duplicate keys, therefore was not parseable (altough most browsers / json viewers just ignored it).

Resources