How can i identify session timeout in AFNetworking 2.0? - ios

i am creating an object of AFHTTPRequestOperationManager *manager
NSString *BaseURLString = #"http://192.168.1.202:81//CredentialsModule/CredentialService.asmx/details";
AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
[manager POST:BaseURLString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
NSDictionary *jsonDict = (NSDictionary *) responseObject;
NSString *products = [jsonDict objectForKey:#"d"];
NSLog(#"pro %#",products);
NSString *newString = [NSString stringWithFormat:#"%#",products];
NSData* data = [newString dataUsingEncoding:NSUTF8StringEncoding];
NSError* error;
id jsonObjects = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"user id %#",jsonObjects);
[self.navigationController pushViewController:CategoryViewController animated:YES];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"\n Error2: %ld",(long)operation.response.statusCode);
NSLog(#"\n Error2: %#", operation.responseString);
}];
suppose i am calling above web service and my session is timeout.So,i want to know is there any chance to identify session timeout before calling the service in afnetworking 2.0.
Please don't try to run web service it won't work because its on local server !!

Related

Multi-part data with image and other parameters in AFNetworking 3.0

I have a problem when uploading image with other parameters. With AFNetworking 3.0
com.alamofire.serialization.response.error.data=<7b227374 61747573 223a2246 41494c55 5245222c 22737461 74757343 6f646522 3a353030 7d>, NSLocalizedDescription=Request failed: internal server error (500)} I am getting
NSMutableDictionary *getUpdates= [[NSMutableDictionary alloc]init];
NSString*userID=#"3";
[getUpdates setObject:userID forKey:#"userId"];
[getUpdates setObject:phoneNumTF.text forKey:#"mobileNumber"];
[getUpdates setObject:nameTF.text forKey:#"name"];
[getUpdates setObject:workZipCodeTF.text forKey:#"work"];
[getUpdates setObject:homeZipCodeTF.text forKey:#"home"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager POST:kUpdateProfile_Post parameters:getUpdates constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:ImageData
name:#"files"
fileName:#"picture" mimeType:#"image/jpeg"];
} progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"Response: %#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: %#", error);
}];
Here i Need to send like this data
picture:filename
json:{ "name": "harish", "work": 92121, "userId": 3, "mobileNumber": 33663366, "home": "500025" }
Any help?
// Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept.
NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
NSString*userID = [def objectForKey:#"UserId"];
NSMutableDictionary *getUpdates= [[NSMutableDictionary alloc]init];
[getUpdates setObject:userID forKey:#"userId"];
[getUpdates setObject:phoneNumTF.text forKey:#"mobileNumber"];
[getUpdates setObject:nameTF.text forKey:#"name"];
[getUpdates setObject:workZipCodeTF.text forKey:#"work"];
[getUpdates setObject:homeZipCodeTF.text forKey:#"home"];
[MBProgressHUD showHUDAddedTo:self.view animated:true];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer]; // only needed if the server is not returning JSON; if web service returns JSON, remove this line
[manager POST:kUpdateProfile_Post parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:getUpdates options:0 error:&error];
NSAssert(jsonData, #"Failure building JSON: %#", error);
NSDictionary *jsonHeaders = #{#"Content-Disposition" : #"form-data; name=\"json\"",
#"Content-Type" : #"application/json"};
[formData appendPartWithHeaders:jsonHeaders body:jsonData];
if (ImageData) {
[formData appendPartWithFileData:ImageData name:#"picture"
fileName:#"image.jpg"
mimeType:#"image/jpeg"];
}
} progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"Response: %#", responseObject);
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseObject
options:kNilOptions
error:&error];
NSLog(#"error appending part: %#", json);
[MBProgressHUD hideHUDForView:self.view animated:true];
[self.navigationController popViewControllerAnimated:YES];
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: %#", error);
[MBProgressHUD hideHUDForView:self.view animated:true];
}];
Finally I got with this code
Two possibilities,
Might be you are sending sending some parameters name different
Server developer doing something wrong at backend
Discuss this issue with him , ask him to debug each line when you made request.
Check below things with your code:
1) Make sure ImageData shouldn't be nil.
2) Check the mine type with your server mine type. It may case that both are different.
3) Check the key name with your api name.

why Json Dictionary is Giving the response in nsdata(Bytes) always.How can i Get the Dictionary from web service

In this i am sending the header and Add perameters to hitting the web service. the problem is after hitting the web service controller is not going in to success part sometimes. if it is hitting properly then it will return the result in bytes.
This is My code::
AFHTTPRequestOperationManager *manager =[AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager.requestSerializer setTimeoutInterval:300];
manager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
//giving the correct format to json
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
token=[parameters valueForKey:#"token"];
if(token == nil || [token isEqual:[NSNull null]]){
token=[[[NSUserDefaults standardUserDefaults]dictionaryForKey:#"LoginWebData"]valueForKey:#"token"];
}else{
token=[parameters valueForKey:#"token"];
}
//set the header do http request
[manager.requestSerializer setValue:[NSString stringWithFormat:#"%#",token]forHTTPHeaderField:#"token"];
[manager POST:[BaseURLString stringByAppendingString:methodName] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject){
NSLog(#"JSON: %#", responseObject);
UserDict=responseObject;
[self.TableviwSideMenu reloadData];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error){
NSLog(#"Error: %#", [error localizedDescription]);
[self showAlert: [error localizedDescription]];
}];
the AFNetworking will do the serialization for you and the responseObject will most likely be either a NSArray or NSDictionary object do like
[manager POST:[BaseURLString stringByAppendingString:methodName] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject){
NSLog(#"JSON: %#", responseObject);
if ([responseObject isKindOfClass:[NSArray class]]) {
NSArray *responseArray = responseObject;
UserDict=responseArray;
/* do something with responseArray */
} else if ([responseObject isKindOfClass:[NSDictionary class]]) {
NSDictionary *responseDict = responseObject;
UserDict=responseDict;
/* do something with responseDict */
}
if (UserDict.count>0)
[self.TableviwSideMenu reloadData];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error){
NSLog(#"Error: %#", [error localizedDescription]);
[self showAlert: [error localizedDescription]];
}];
The AFNetworking framework and its delegate will handle everything. You will get responseObject in NSDictionary.
-(void)Request{
[self.Request_coursecomplete setRequestMethod:#"POST"];
self.Request_coursecomplete = [ASIFormDataRequest requestWithURL:sendSMSURL];
self.Request_coursecomplete.delegate = self;
//will try second time
[self.Request_coursecomplete setNumberOfTimesToRetryOnTimeout:2];
[self.Request_coursecomplete setShouldContinueWhenAppEntersBackground:YES];
NSTimeInterval timeOutSecs = 60000;
[self.Request_coursecomplete setTimeOutSeconds:timeOutSecs];
[self.Request_coursecomplete startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSString *receivedString = [request responseString];
NSLog(#"json string: %#",receivedString);
NSDictionary *d = [receivedString JSONValue];
}

Array In Post Data Afnetworking Gives Error - Required Data Missing

Hii I am using afnetworking from post array data to sent server side here is my code ...
NSMutableDictionary *dict1=[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"online_status",#"option_name",dict[#"option_value"],#"option_value", nil];
NSArray *arr1=[[NSMutableArray alloc]initWithObjects:dict1, nil];
NSMutableDictionary *dict2=[[NSMutableDictionary alloc]initWithObjectsAndKeys:[UserDefaults valueForKey:#"user_id"],#"user_id",arr1,#"option_array", nil];
NSError *error = nil;
NSString *createJSON = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:dict2
options:NSJSONWritingPrettyPrinted
error:&error]
encoding:NSUTF8StringEncoding];
NSDictionary *pardsams = #{#"data": createJSON};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSLog(#"Dict %#",pardsams[#"data"]);
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[manager POST:[NSString stringWithFormat:#"%#set_user_multiple_options",K_APP_URL] parameters: pardsams[#"data"] success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
and getting server responce is :
message = "Required parameters missing.";
status = 0;
i will hit the request to rest client but where getting correct responce saved data bt trying to do in code it not working polease... help me

iOS : How to correctly send put request to server

I have a put request that I am trying to achieve. The problem I am having is it isn't sending the correct raw body over to the server form/post parameter. What I am expecting is a raw body that is {"questions":[{"type":"control_head"}]}, instead I am getting questions[][type]=control_head any tips or suggestions are appreciated.
NSString *jsonString = #"{\"questions\":[{\"type\":\"control_head\"}]}";
[self createForms:jsonString];
- (void) createForms : (NSString *) form
{
[self executePutRequest:#"user/forms" params:form];
}
- (void) executePutRequest : (NSString *) url params : (NSString *) params
{
NSString *urlStr = [NSString stringWithFormat:#"http://requestb.in/13oujhot"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSData *data = [params dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSMutableDictionary *userinfo = [[NSMutableDictionary alloc] init];
[manager PUT:urlStr parameters:json success:^(AFHTTPRequestOperation *operation, id responseObject) {
[operation setUserInfo:userinfo];
SBJsonParser *jsonparser = [SBJsonParser new];
id result = [jsonparser objectWithString:[operation responseString]];
if ( self.delegate != nil && [self.delegate respondsToSelector:finishSelector] ) {
[self.delegate performSelector:finishSelector withObject:result];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[operation setUserInfo:userinfo];
if ( self.delegate != nil && [self.delegate respondsToSelector:failSelector] ) {
[self.delegate performSelector:failSelector withObject:[operation error]];
}
}];
}
Copied From here
Updated again for AFNetworking 2.0 - see bottom
For AFNetworking 1.0:
NSURL *url = [NSURL URLWithString:#"https://mysite.com/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
height, #"user[height]",
weight, #"user[weight]",
nil];
[httpClient postPath:#"/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"Request Successful, response '%#'", responseStr);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"[HTTPClient Error]: %#", error.localizedDescription);
}];
For AFNetworking 2.0 (and also using the new NSDictionary syntax):
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"user[height]": height,
#"user[weight]": weight};
[manager POST:#"https://mysite.com/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
you can use afnetworking framework, it will help you.
http://www.raywenderlich.com/59255/afnetworking-2-0-tutorial
NSString *str_URL = [NSString stringWithFormat:#"YOUR URL"]];
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:
Your Value,KEY_Name,
nil];
AFHTTPRequestOperationManager *Manager = [AFHTTPRequestOperationManager manager];
[Manager PUT:str_URL parameters:parameters
success: ^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"%#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"%#", error.description);
}];

afnetworking cache request to disc

I'm currently using the code below to load data from a webservice (over https).
I need a way to cache this data to disc.
Ideally the flow would be like this.
Has data loaded?
If no - read from cache
If no internet connection - read from cache
If yes - continue as normal
How would this be possible?
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:#"someurl" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//NSLog(#"Error: %#", error);
}];
To write the data to a file, you could NSJSONSerialization to convert your response object into NSData, then save the data to a file:
NSString* filePath [NSTemporaryDirectory() stringByAppendingPathComponent:#"someFile.json"];
NSData* data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
[data writeToFile:filePath options:0 error:nil];
Then, before you make the request, check if the file exists and read from it instead of doing your request:
NSData* jsonData = [NSData dataWithContentsOfFile:filePath];
if(jsonData == nil){
// Perform network request
}else{
id responseObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
}

Resources