How to make HTTP Post request with JSON body in Swift like in this there are not using frameworks like this i need xml posting can any one help me...
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"Your SERVER"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request addValue:#"application/xml" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
NSString *xmlString = #"<?xml version=\"1.0\"?>\n<yourdata></yourdata>";
[request setHTTPBody:[xmlString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// handel response & error
}];
[postDataTask resume];
Use the above code to achieve what you want
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];
}
When i call getProfile method from viewDidLoad
- (void)viewDidLoad {
[super viewDidLoad];
[self getProfile];
}
it success
-(void)getProfile
{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSString *tempurl= [NSString stringWithFormat:#"%#11155/person/#self",baseUrlSecure];
tempurl = [tempurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:tempurl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:gWCToken forHTTPHeaderField:#"WCToken"];
[request addValue:gWCTrustedToken forHTTPHeaderField:#"WCTrustedToken"];
[request setHTTPMethod:#"GET"];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error)
{
NSLog(#"Error: %#", error);
dispatch_async(dispatch_get_main_queue(), ^{
[Alert showAlertWithTitle:#"M2All" andWithMessage:error.localizedDescription onView:self andErrorCode:[NSString stringWithFormat:#"%ld",error.code]];
});
}
else
{
NSDictionary *dictResult = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSArray *arrError = [dictResult objectForKey:#"errors"];
if(arrError.count >0)
{
dispatch_async(dispatch_get_main_queue(), ^{
[Alert showAlertWithTitle:#"M2All" andWithMessage:[[arrError objectAtIndex:0] objectForKey:#"errorMessage"] onView:self andErrorCode:[[arrError objectAtIndex:0] objectForKey:#"errorCode"]];
});
return;
}
}
}];
[postDataTask resume];
}
but same calling from webViewDidFinishLoad then getting error
i don't know what is the problem
- (void)webViewDidFinishLoad:(UIWebView *)webView{
[self getProfile];
}
Clear the browser cookies and try again. I faced the similar problem. I cleared the browser cache and it's working fine for me
How to Design the Overlay Instructions Above The View?
I HAD 6 buttons....For Each Button I have To show Overlay For That, Before i click on that Button
Suppose... 1) Click button is there...above the Click Button we need
to show overlay for click on that button Like That...
**
[I Need Like This Overlay menu over the all Buttons][1]
[1]: http://i.stack.imgur.com/dIjRF.jpg
**
Use NSURLSession instead. NSURLConnection is deprecated.
NSString *stringURL = [NSString stringWithFormat:#"%#?term=%#", BASE_URL, _inputText.text];
NSURL *URL = [NSURL URLWithString:stringURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:#"POST"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromData:yourData completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// Do your stuff here
}];
why not use alamofire---
NSDictionary *parameters = #{
#"email": #"myemail1#mailinator.com",
#"password": #"123456789",
#"accountnumber": #"LiM6N5gBBmqdlQBJGkqcP0h4OKwGbnzoWFcgTG3Z",
#"ifcscode": #"ABC"
};
NetworkHandler *networHandler = [NetworkHandler sharedInstance];
[networHandler composeRequestWithMethod:#"http://example.com/enpoint.json"
paramas: parameters
onComplition:^(BOOL success, NSDictionary *response){
if (success) { //handle success response
[self handleLoginResponse:response];
}
else{
ProgressIndicator *pi = [ProgressIndicator sharedInstance];
[pi hideProgressIndicator];
}
}];
you can use postman to check your api
Pass this two variables of FirstViewController to SecondViewController and then try to put below code in place of your code.
Below is code to POST data using NSURLSession.
I hope this works for you.
-(void)postData
{
NSString *content = [NSString stringWithFormat:#"Name=%#&Email=%#&A/CName=%#&A/CNumber=%#&IFSCCode=%#&TypeOfAccount=%#",name,email,acName,acNumber,ifscCode,typeOfAccount];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:#"your web service url"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[content dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:londonWeatherUrl]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
NSMutableDictionary *dictJson = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(#"Dict Json :- %#",dictJson);
}] resume];
}
Send Parameter to web service using POST method
Below is code to POST data to web service using NSURLConnection.
-(void)postData
{
NSString *content = [NSString stringWithFormat:#"email=%#&name=%#",textEmail.text,textName.text];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:#"your web service url"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[content dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection connectionWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
dictJson = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(#"Dict Json :- %#",dictJson);
}
When I try to call web service using NSURLSession with POST on Apple Watch, response parameter is nil. What might be the issue with this ?
Code for calling web service:
NSURL *url = [NSURL URLWithString:#"https://demo.test.com:22322/api/Alerts/UpdateAlertStatus?intUserId=5¶maccessTokenId=24460c5f-be71-45b5-99cf-f46c277c3d9e&UserId=100200"];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = #"POST";
NSMutableDictionary *mutDictParameters = [[NSMutableDictionary alloc] init];
[mutDictParameters setObject:#"708" forKey:#"AlertId"];
[mutDictParameters setObject:#"2878" forKey:#"XmlMessageId"];
[mutDictParameters setObject:#"5" forKey:#"UserId"];
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:mutDictParameters
options:kNilOptions error:&error];
if (!error) {
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
fromData:data completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
// Handle response here
NSLog(#"Response : %#",response);
}];
[uploadTask resume];
}