Activity Indicator on a button click in IOS - ios

I have a button of submitting form data to the service. When user click it it submit data and give alert of success. I want to add activity indicator in it , when user click button of submit the time it takes to submit the data the activity indicator should move and than hide when it data is submitted.I'm confused where should i use it in the code , I'm confused at that whether it shall be call after response or anywhere else. My code is,
NSString *post = [NSString stringWithFormat:#"propertyfor=%#&propertytype=%#&landarea=%#&country=%#&city=%#&price=%#&description=%#&location=%#&name=%#&email=%#&phone=%#",_propertyfor,_propertytype,_landarea,_country,_city,_price,_propdes,_propdescrip,self.name.text,self.email.text,phone];
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:#"My URL"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
}] resume];

**//Start Activity Indicator here.**
NSString *post = [NSString stringWithFormat:#"propertyfor=%#&propertytype=%#&landarea=%#&country=%#&city=%#&price=%#&description=%#&location=%#&name=%#&email=%#&phone=%#",_propertyfor,_propertytype,_landarea,_country,_city,_price,_propdes,_propdescrip,self.name.text,self.email.text,phone];
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:#"My URL"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
**//Stop Activity Indicator here.**
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
}] resume];

You need to start animating before session created and stop animating one you get reply. In your code :
.
.
.
.
[activity startAnimating];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
dispatch_async(dispatch_get_main_queue(), ^{
[activity stopAnimating];
});
NSLog(#"requestReply: %#", requestReply);
}] resume];

Replace followind code with original:
CGSize s1 = UIApplication.sharedApplication.windows[0].frame.size;
CGRect r1 = CGRectMake(s1.width/2-20, s1.height/2-20, 40, 40);
UIActivityIndicatorView *act = [[UIActivityIndicatorView alloc]initWithFrame:r1];
[self.view addSubview:act];
[act startAnimating];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
[act stopAnimating];
[act removeFromSuperview];
}] resume];

Related

I want to upload image with other parameters to server using objective c

well am new to iOS and i encountered a situation where i have to upload a image to server. Here is what am doing in the post method.
- (IBAction)submitClicked:(UIButton *)sender {
NSDictionary *inputData = [NSDictionary dictionaryWithObjectsAndKeys:myImage,#"coverPic", nil];
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://api.mapartment.in/index.php/events/create"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:70.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSData *jsonInputData = [NSJSONSerialization dataWithJSONObject:inputData options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonInputString = [[NSString alloc] initWithData:jsonInputData encoding:NSUTF8StringEncoding];
[request setHTTPBody:[jsonInputString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
dispatch_async(dispatch_get_main_queue(), ^{
NSDictionary *jsondictcity_name = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
if([[jsondictcity_name valueForKey:#"result"] isEqual:#"true"]){
NSLog(#"Success");
}
else{
NSLog(#"Try Again");
}
[self.view resignFirstResponder];
});
}
];
[postDataTask resume];
}
P.S. _localFilePath contains - /Users/appcode/Library/Developer/CoreSimulator/Devices/3C3567B8-03BC-4233-B0BC-97E3899D0AAA/data/Containers/Data/Application/3D574024-42FB-4305-807A-ACC3C128383F/Documents/png
Image will not pass with other parameter,you have to convert image into NSData
UIImage *yourImage= [UIImage imageNamed:#"image.png"];
NSData *imageData = UIImagePNGRepresentation(yourImage);
NSString *postLength = [NSString stringWithFormat:#"%d", [imageData length]];
and then pass these data in request
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:imageData];
and other parameter pass as json.
to get UIImage from path use
UIImage *yourImage = [UIImage imageWithContentsOfFile: imageFilePath];
- (IBAction)submitClicked:(UIButton *)sender {
UIImage* image = [UIImage imageWithContentsOfFile:_localFilePath];
NSString *myImage = [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
NSDictionary *inputData = [NSDictionary dictionaryWithObjectsAndKeys:myImage,#"coverPic",#"POEM WRITING",#"title",#"Bring your own paper",#"desc", nil];
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://api.mapartment.in/index.php/events/create"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:70.0];
[request addValue:#"multipart/form-data" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSData *jsonInputData = [NSJSONSerialization dataWithJSONObject:inputData options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonInputString = [[NSString alloc] initWithData:jsonInputData encoding:NSUTF8StringEncoding];
[request setHTTPBody:[jsonInputString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
dispatch_async(dispatch_get_main_queue(), ^{
NSDictionary *jsondictcity_name = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
if([[jsondictcity_name valueForKey:#"result"] isEqual:#"true"]){
NSLog(#"Success");
}
else{
NSLog(#"Try Again");
}
[self.view resignFirstResponder];
});
}
];
[postDataTask resume];
}

How to fetch Data from the web services using NSURLSession?

I have made one demo code for print the data from the web Services,
Code
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://54.149.46.64/API/video.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"video" forHTTPHeaderField:#"list"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
}] resume];
Output
JSON_Webservices[4496:150468] requestReply: {"Status":"Fail","Message":"Please enter required fields"}
Why i am not able to fetch data from the WS? Please help me.
Working Fine In Postman
Image
Thank You.
header
Please check this...
NSURL *aUrl = [NSURL URLWithString:#"XXXX"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSString *postString = #"list=video";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
NSError *jsonError;
NSData *objectData = [requestReply dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
NSLog(#"requestReply: %#", json);
}] resume];

Control flow during json parsing - Objective C

I am trying to create a login screen where one has to enter his UserName and Password. On clicking the login button I am parsing the details to the server. Here's the code
NSString *post = [NSString stringWithFormat:#"username=%#&password=%#",[_userNameText text],[_passwordText 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://*******/*****/******/userLogin.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"sample data"];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data , NSURLResponse *response , NSError *error){
_requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"%#",_requestReply);
}] resume];
So far the code works just as intended. Now I want to check if the "requestReply" that is returned from the server has the value "success" for it's "status" key. So I tried to print it's value with the following code.
_responseData = _requestReply;
NSLog(#"%#" , _responseData[#"status"]);
And here's the console output
2016-10-21 06:44:03.424 QuizApp2[65724:1287972] (null)
2016-10-21 06:44:03.501 QuizApp2[65724:1288003] {"status":"success","message":"Welcome admin","code":true}
I am not sure, but I felt that the last line of the code is executing before the parsing happens. Can someone please highlight how the control flows here? Or is there anything wrong with my code?
I didn't see any code about parse data. Do you mean this line
_requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
If the userLogin.php returns a JSON data, just do this:
[[session dataTaskWithRequest:request completionHandler:^(NSData *data , NSURLResponse *response , NSError *error){
NSError *err = nil;
id jsonData = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err];
if (err) {
NSLog(#"%#", err);
}
else {
NSLog(#"%#", jsonData[#"status"]);
}
}] resume];

Use of activity indicator in json parsing

I am working on application and i have to use activityindicator when login is in progress, i am not getting where i have to use the code for activityindicator in the below code:-
- (IBAction)Login:(id)sender
{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:BaseUrl#"login"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"userName=g&userPassword=123456&api_key=ZWZ&api_password=1" ];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"text= %#",text);
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(error!=nil)
{
NSLog(#"error = %#",error);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self checkUserSuccessfulLogin:json];
});
}
else{
NSLog(#"Error : %#",error.description);
}
}];
[postDataTask resume];
}
It is taking time to go the other page after login.
please help me.
Use this below code
//main thread
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
spinner.center = CGPointMake([[UIScreen mainScreen]bounds].size.width/2, [[UIScreen mainScreen]bounds].size.height/2);
//if you want to add to window, use this below one
[appdelegate.window addSubview:spinner];
//or if you want to add to view, use below one
[self.view addSubView:spinner];
[spinner startAnimating];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0),^{
dispatch_async(dispatch_get_main_queue(), ^{
//after your server call or parsing or something you can call this to stop animating
[spinner stopAnimating];
});
});
aakash,
You can make use of MBProgressHUD third party framework you need not write the code for activity inddicator adding it to screen and all (no need to re invent the wheel) here is a link :) https://github.com/jdg/MBProgressHUD
add a pod dependency or add the files to your project however you feel comfortable.
import files.
#import <MBProgressHUD/MBProgressHUD.h>
- (IBAction)Login:(id)sender
{
//add the MBProgressHud here before you make the webservice call
MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
hud.labelText = NSLocalizedString(#"Login in progress", nil);
[self.navigationController.view addSubview:self.HUD];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:BaseUrl#"login"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"userName=g&userPassword=123456&api_key=ZWZ&api_password=1" ];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
//finally hide it, whether its sucess or failure just remove it
[MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
});
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"text= %#",text);
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(error!=nil)
{
NSLog(#"error = %#",error);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self checkUserSuccessfulLogin:json];
});
}
else{
NSLog(#"Error : %#",error.description);
}
}];
[postDataTask resume];
}
I have updated code for Activity indicator.
Just make the outlet of the Activity Indicator in .h file.
#property (weak,nonatomic) UIActivityIndicatorView *indicator;
then, write below code in .m file's viewDidLoad().
self.indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
self.indicator.center = CGPointMake([[UIScreen mainScreen]bounds].size.width/2, [[UIScreen mainScreen]bounds].size.height/2);
Below is the code for Json parsing:
- (IBAction)Login:(id)sender
{
[self.indicator startAnimating];//The ActivityIndicator Starts Animating Here
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:BaseUrl#"login"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"userName=g&userPassword=123456&api_key=ZWZ&api_password=1" ];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
dispatch_async(dispatch_get_main_queue(), ^{
[self.indicator stopAnimating];//The ActivityIndicator Stops Animating when Response Arrives
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"text= %#",text);
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
[self checkUserSuccessfulLogin:json];
});
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
[self.indicator stopAnimating];
});
NSLog(#"Error : %#",error.description);
}
}];
[postDataTask resume];
}
- (IBAction)Login:(id)sender
{
//show or add youar activity indicator here
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:BaseUrl#"login"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"userName=g&userPassword=123456&api_key=ZWZ&api_password=1" ];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Hide or remove your activity indicator here
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"text= %#",text);
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(error!=nil)
{
NSLog(#"error = %#",error);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self checkUserSuccessfulLogin:json];
});
}
else{
NSLog(#"Error : %#",error.description);
}
}];
[postDataTask resume];
}
As i add comments in your code, show your activity indicator at very start of method as user tap button it starts and hide it from completion handler because completion handler calls after response is came from server.
Hope this will help :)
Try This Code
-(IBAction)Login:(id)sender
{
UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
CGRect activityFrame = CGRectMake(130,10,40,40);
[activityView setFrame: activityFrame];
dispatch_async(dispatch_get_main_queue(), ^{
[self.view addSubview:activityView];
activityView.center = self.view.center;
[activityView startAnimating];
[self.view bringSubviewToFront:activityView];
});
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:BaseUrl#"login"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"userName=g&userPassword=123456&api_key=ZWZ&api_password=1" ];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"text= %#",text);
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(error!=nil)
{
NSLog(#"error = %#",error);
}
dispatch_async(dispatch_get_main_queue(), ^{
[activityView stopAnimating];
[activityView removeFromSuperview];
[self checkUserSuccessfulLogin:json];
});
}
else{
NSLog(#"Error : %#",error.description);
}
}];
[postDataTask resume];
}

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.

Resources