How DISPATCH_TIME_FOREVER will work in ios app? - ios

Hi in my application i am using DISPATCH_TIME_FOREVER for ever API call. It seems it blocking the main thread when network is slow.I don't have much idea about this DISPATCH_TIME_FOREVER. Can anyone guide me.Here is the code which i am using.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSMutableDictionary *postDic=[[NSMutableDictionary alloc]init];
[postDic setObject:#"getProfileDetails" forKey:#"cmd"];
[postDic setObject:[[NSUserDefaults standardUserDefaults]objectForKey:#"accountnumber"] forKey:#"accountNumber"];
[postDic setObject:[[NSUserDefaults standardUserDefaults]objectForKey:#"deviceID"] forKey:#"deviceId"];
NSData *postData;
dispatch_group_t group=dispatch_group_create();
if(postDic!=nil)
postData=[NSJSONSerialization dataWithJSONObject:postDic options:0 error:nil];
NSString *postLength=[NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
// remote ip
NSString *remoteAddress=[NSString stringWithFormat:#"%#",[[NSUserDefaults standardUserDefaults]objectForKey:#"remoteIP"]];
NSURL *url=[NSURL URLWithString:remoteAddress];
NSMutableURLRequest *request =[[NSMutableURLRequest alloc]init];
[request setURL:url];
[request setHTTPMethod:#"Post"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:[NSString stringWithFormat:#"%# %#",[[NSUserDefaults standardUserDefaults] valueForKey:#"tokenType"],[[NSUserDefaults standardUserDefaults] valueForKey:#"accessToken"]] forHTTPHeaderField:#"Authorization"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setTimeoutInterval:10.0];
[request setHTTPBody:postData];
dispatch_group_enter(group);
NSURLSessionConfiguration *profileConfiguration=[NSURLSessionConfiguration defaultSessionConfiguration];
profileConfiguration.timeoutIntervalForResource=30.0;
profileConfiguration.timeoutIntervalForRequest=30.0;
NSURLSession *profileSession=[NSURLSession sessionWithConfiguration:profileConfiguration];
NSURLSessionDataTask *profileTask=[profileSession dataTaskWithRequest:request
completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
{
NSLog(#"profile Error is %#",error);
NSDictionary* lineUpStationsResponse;
if(data!=nil)
profileResponse=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
// If result is null then send empty dictionary back to viewcontroller to display that login customer not subscribed to any service
if(error!=nil)
{
completionBlock(postDic,nil,error);
}
if([NSJSONSerialization isValidJSONObject:lineUpStationsResponse])
{
completionBlock(postDic,profileResponse,error);
}
else
{
NSDictionary *resultDic=[[NSDictionary alloc]init];
completionBlock(postDic,resultDic,error);
}
// NSLog(#"profile is %#",profileResponse);
dispatch_group_leave(group);
}];
[profileTask resume];
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
});

Related

How to POST { "username"="usernameValue" "password"="passsworValue" } as json body in objective c

I tried Like this..
-(void)GetCartIdDetails{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *post = [NSString stringWithFormat:#"username=%#&pasword=%#",self.TextUsername.text,self.TextPassword.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://192.168.0.21/mahroosa/rest/V1/integration/customer/token"]];
[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//MultiThreading
if (postData){
dispatch_async(dispatch_get_main_queue(), ^{
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
//removing Double Qoutes From String
NSString *Replace =[requestReply stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSLog(#"requestReply: %#", Replace);
}] resume];
});
}
});
}
Using AFNetworking:
-(void)Gettok {
NSString* URLString = [NSString stringWithFormat:#"http://192.168.0.21/mahroosa/rest/V1/integration/customer/token"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
manager.requestSerializer = requestSerializer;
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
[params setObject:self.TextUsername.text forKey:#"username"];
[params setObject:self.TextPassword.text forKey:#"password"];
[manager POST:URLString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSError * error;
NSArray *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
NSLog(#"--------------------respons : %#--------------------",result);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"----------------------Error ; %#------------------------------",error);
}];
}
The content type of the request body. Set this value "Content-Type:application/json"
In response i get decode error message.I already got the get JSON getrequest working in AFNetworking but this post request is giving me some problems. Thanks for help in advance.
In the first NSURLSession style you don't send json to the service. Try it like this:
-(void)GetCartIdDetails{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSDictionary *dict = #{#"username":self.TextUsername.text,
#"password":self.TextPassword.text};
NSData *postData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://192.168.0.21/mahroosa/rest/V1/integration/customer/token"]];
[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//MultiThreading
if (postData){
dispatch_async(dispatch_get_main_queue(), ^{
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
//removing Double Qoutes From String
NSString *Replace =[requestReply stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSLog(#"requestReply: %#", Replace);
}] resume];
});
}
});
}

How to request datas to server in post method ios?

Hi I am new to ios post method.In my app i want to show list of values.
The request format is:
{"customerId":"000536","requestHeader":{"userId":"000536"}}
The code i used is:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSString *post =[[NSString alloc] initWithFormat:#"customerId=%#&userId=%#",#"000536",#"000536"];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"https://servelet/URL"];
NSDictionary *jsonDict = [[NSDictionary alloc] initWithObjectsAndKeys:
#"000536", #"customerId",
#"000536", #"userId",
nil];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json; character=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response,NSData *data, NSError *error){
// NSLog(#"Response code: %ld", (long)[response statusCode]);
if(error || !data){
NSLog(#"Server Error : %#", error);
}
else
{
NSLog(#"Server Response :%#",response);
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
NSArray* latest = [json objectForKey:#"apptModel"];
NSLog(#"items: %#", latest);
}
}
];
The response is : (null)
How to request the values with same format as shown above?Thanks in advance.
Use This Code
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSString *post =[[NSString alloc] initWithFormat:#"customerId=%#&userId=%#",#"000536",#"000536"];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"https://servelet/URL"];
NSDictionary *jsonDict = [[NSDictionary alloc] initWithObjectsAndKeys:
#"000536", #"customerId",
#"000536", #"userId",
nil];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json; character=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *err)
{
// NSLog(#"Response code: %ld", (long)[response statusCode]);
if(error || !data){
NSLog(#"Server Error : %#", error);
}
else
{
NSLog(#"Server Response :%#",response);
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
NSArray* latest = [json objectForKey:#"apptModel"];
NSLog(#"items: %#", latest);
}
}];
[task resume];

Response is not coming from server using NSurlSession

Hi i am very new for ios and in my app i have used ASIFormDataRequest earlier days for integrating the services
now i have changed format and i am using NSURLSession instead of ASIFormDataRequest
But when i request change password to server using ASIFormDataRequest success response is coming from server but when i use NSURLSession failed response coming from server please help what is wrong
NSURlsession:-
def = [NSUserDefaults standardUserDefaults];
NSString *myString = [def stringForKey:#"AccesToken"];
NSString *AccessToken = [NSString stringWithFormat:#"Bearer %#",myString];
NSString *Finalstr = [NSString stringWithFormat: #"MedicaidId=%#&OldPassword=%#&NewPassword=%#&ConfirmPassword%#", medicaId,self.CurPwdTxt.text,self.NewPwdTxt.text,self.ConfPwdTxt.text];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:mainurl,BaseURL]]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[Finalstr dataUsingEncoding:NSUTF8StringEncoding]];
[request addValue:AccessToken forHTTPHeaderField:#"Authorization"];
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"dataTaskWithRequest error: %#", error);
}
else if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200) {
NSError *parseError;
id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"responseobject is %#",responseObject);
}else{
NSError *parseError;
id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"else condtion");
if (!responseObject) {
NSLog(#"JSON parse error: %#", parseError);
NSLog(#"responseobject is%#",responseObject);
} else {
NSLog(#"responseobject is %#",responseObject);
}
//if response was text/html, you might convert it to a string like so:
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"final responseString = %#", responseString);
}
}
}];
[task resume];
}
ASIFormDataRequest:-
NSString *urlStr = [NSString stringWithFormat:#"myurl",BaseURL];
NSLog(#"urlStr --->>> %#",urlStr);
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlStr]];
[request setRequestMethod:#"POST"];
def = [NSUserDefaults standardUserDefaults];
NSString *myString = [def stringForKey:#"AccesToken"];
NSString *str = [NSString stringWithFormat:#"Bearer %#",myString];
NSLog(#"token is %#",str);
[request setPostValue:medicaId forKey:#"MedicaidId"];
[request setPostValue:self.CurPwdTxt.text forKey:#"OldPassword"];
[request setPostValue:self.NewPwdTxt.text forKey:#"NewPassword"];
[request setPostValue:self.ConfPwdTxt.text forKey:#"ConfirmPassword"];
[request addRequestHeader:#"Authorization" value:str];
[request setDelegate:self];
[request startAsynchronous];
You are sending different requests there. In the 'new' code, you are constructing the POST data like this:
#"MedicaidId=%#&OldPassword=%#&NewPassword=%#&ConfirmPassword%#"
which looks like GET-parameters more than form-encoding (which you use on the 'old' request).
Tracking your request and checking out the actual request using something like Wireshark might help you out to spot the problem yourself next time.

Fetch data using Post method in Objective-c

I am fetching data using POST method. And I have successfully retrieved all the data.It's taking too long to display it in UI but I can print it immediately on console, my code is
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.xxxyyy.com/v1/api/client/authorize"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"ABCD" forHTTPHeaderField:#"Authkey"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"Authkey"];
NSData* data1 = [requestReply dataUsingEncoding:NSUTF8StringEncoding];
jsonReturnArray = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingAllowFragments error:&error];
NSArray *array = [jsonReturnArray copy];
[self rec:array];
NSString *phoneNumber=[NSString stringWithFormat:#"%#",[jsonReturnArray valueForKey:#"phone"]];
lblPhoneNumber.text = phoneNumber;
NSString *Address=[NSString stringWithFormat:#"%# %# %#,CA %#",[jsonReturnArray valueForKey:#"street1"],[jsonReturnArray valueForKey:#"street2"],[jsonReturnArray valueForKey:#"city"],[jsonReturnArray valueForKey:#"postalcode"]];
lblAddress.text=Address;//takes long time to display
NSLog(#"%#",Address);//immeaditely print
strlatitude=[jsonReturnArray valueForKey:#"latitude"];
strlongitude=[jsonReturnArray valueForKey:#"longitude"];
[self Map:(MKMapView *)mapLocation didUpdateUserLocation:(MKUserLocation *)nil];//method call
}] resume];
This is take too time to print data, but if you use NSURLConnection class it may be help you.This is my Class method it may be helpful.
+ (void)postRequestData:(NSDictionary *)postVars
Action:(APIMode)action
WithCompletionHandlar:(void (^) (id result, BOOL status))completionBlock
{
NSURL *url = [NSURL URLWithString:API_URL([self getAPINameForType:action])];
NSLog(#"Request URL %#",[NSString stringWithFormat:#"%#",url]);
NSString *contentType = #"application/json";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSError *err = nil;
NSMutableDictionary *params=[[NSMutableDictionary alloc] initWithDictionary:postVars];
// [params setObject:[self getAPINameForType:action] forKey:#"mode"];
NSLog(#"Paramater %#",params);
NSData *body = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&err];
[request setHTTPBody:body];
[request addValue:[NSString stringWithFormat:#"%lu", (unsigned long)body.length] forHTTPHeaderField: #"Content-Length"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if(!connectionError)
{
NSError *error = nil;
NSDictionary *dictResponse = [NSDictionary dictionaryWithDictionary:[NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments error:&error]];
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock(dictResponse,(error == nil));
});
NSLog(#"%#",dictResponse);
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock(connectionError.localizedDescription,NO);
});
}
}];
}
Use this method instead of it.It is executed fast because NSURLConnection Class execute in background.
Try to fetch your data using NSURLConnection class(manual code) or simply use AFNetworking class(less code). AFNetworking internally uses NSURLConnection class itself.

How to check if there is no server response in Objective c

I am trying to hit a web service . All works good. But if the server is not working then my app crashes .
How to handle NO SERVER RESPONSE .
Please help
Here is my code for hitting web service.
NSMutableDictionary *get = [[NSMutableDictionary alloc]init];
[get setObject:#"0" forKey:#"unit"];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:get options:kNilOptions error:nil];
NSString *jsonInputString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *post = [[NSString alloc]initWithFormat:#"req=%#",jsonInputString];
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"%#",getCommunity]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (responseData != nil) {
NSDictionary *jsonRecieveDict = (NSDictionary*)[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"jsonArray =======%#",jsonRecieveDict);
}
if (error)
{
UIAlertView *errorAlert = [[UIAlertView alloc]initWithTitle:#"Servor not responding" message:nil delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[errorAlert show];
}
** ERROR IS BECAUSE OF INVALID STATUS CODE FROM SERVER **
if (error != nil) {
// Something went wrong...
NSLog(#"Servor not responding %#",error.description);
return;
}
if ([response statusCode] >= 300) {
NSLog(#"Servor not responding, status code: %ld", (long)[response statusCode]);
return;
}
First condition should be error checking,Second if response comes check the status code then only perform the remaining operation
Also change NSURLResponse *response; to NSHTTPURLResponse *response
OR diff Implementation
NSMutableDictionary *get = [[NSMutableDictionary alloc]init];
[get setObject:#"0" forKey:#"unit"];
if([NSJSONSerialization isValidJSONObject:get]){
//convert object to data
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:kNilOptions error:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"your url"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
NSURLSessionConfiguration *config=[NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session=[NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(response){
NSString *resp = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
NSLog(#"Echo %#",resp);
}
else{
NSLog(#"Timeout");
}
}];
[task resume];
}

Resources