Rest call from webViewDidFinishLoad cause error - ios

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

Related

NSURLSessionDataTask completion handler not getting called for the first time

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[request setHTTPBody:jsonData];
// configure NSURLSessionConfiguration with request timeout
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
// set request timeout
defaultConfigObject.timeoutIntervalForRequest = 120.0;
// create NSURLSession object
// Working fine with below instance of default session but its taking a lot of time to fetch response.
//NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
// set NSURLSessionDataTask
#try {
NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//
}];
[dataTask resume];
}
The task never completes because it never gets started. You have to manually start the data task using its resume() method.
And Don't use the dataTask object inside the try block.
if ([self checkNetworkStatus]) {
#try {
// Create the data and url
NSString *encryptedString = [self createRequest:userContext objectType:deviceObjectType projectType:projectId];
NSDictionary *dictRequest = #{REQ_KEY_REQUEST: encryptedString};
requestString = [JSONHelper dictionaryToJson:dictRequest];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#Data",globals.API_Base_URL]];
// Create Request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
request.HTTPMethod = #"POST"; // For Post
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
int strLength = (int)requestString.length;
[request setValue:[NSString stringWithFormat:#"%d", strLength] forHTTPHeaderField:#"Content-Length"];
NSData *dataRequest = [requestString dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = dataRequest;`enter code here`
id delegateValue = self;
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
delegate:delegateValue
delegateQueue:[NSOperationQueue mainQueue]];
//NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:
^(NSData *responseData, NSURLResponse *response, NSError *error) {
// ...
[self destroyNetworkCache];
// [[NSURLCache sharedURLCache] storeCachedResponse:nil forRequest:urlReq];
[[NSURLCache sharedURLCache] removeAllCachedResponses];
dispatch_async(dispatch_get_main_queue(), ^(void)
{
if (! error)
{
[self parseResponse:responseData forObjectType:deviceObjectType andTag:tag withDelegate:del];
}
else
{
NSString *errMsg = error.description;
if (errMsg.length <= 0) {
errMsg = NSLocalizedString(#"msg_network_error", #"msg_network_error");
}
else if (errMsg.length > 0 && [errMsg rangeOfString:#"timed out"].length != 0)
{
errMsg = NSLocalizedString(#"msg_request_timed_out", #"msg_request_timed_out");
}
else if ([self checkForURLDomainError:errMsg])
{
errMsg = NSLocalizedString(#"msg_network_error", #"msg_network_error");
}
if (tag < 0)
{
if ([del conformsToProtocol:#protocol(WTConnectionServiceDelegate)])
{
if ([del respondsToSelector:#selector(wtConnectionService:forObjectType:didFailedWithError:)])
{
[del wtConnectionService:nil forObjectType:deviceObjectType didFailedWithError:errMsg];
return;
}
}
}
else
{
if ([del conformsToProtocol:#protocol(WTConnectionServiceDelegate)])
{
if ([del respondsToSelector:#selector(wtConnectionService:forObjectType:andTag:didFailedWithError:)])
{
[del wtConnectionService:nil forObjectType:deviceObjectType andTag:tag didFailedWithError:errMsg];
return;
}
}
}
}
});
}];
[task resume];
}
#catch (NSException *exception) {
[self handleException:exception];
}
#finally {
}
}
Below Is delegate methods
-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
}
-(void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error{
}

NSURLSessionDataTask Memory Leaks

I am trying to do simple thing with NSURLSessionDataTask to get some data from server. Previously I was using NSURLConnection to get that data, but wanted to move my code to NSURLSessionDataTask. So here the code
NSString *_urlString = [NSString stringWithFormat:#"%#/integration/admin/token",BaseURL];
NSMutableURLRequest *_request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:_urlString]];
[_request setHTTPMethod:#"POST"];
[_request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSData *_sendingData = [NSJSONSerialization dataWithJSONObject:#{#"username":#"demo", #"password":#"demo123"} options:0 error:NULL];
[_request setHTTPBody:_sendingData];
NSURLSessionConfiguration *_defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *_session = [NSURLSession sessionWithConfiguration:_defaultConfig delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *_dataTask = [_session dataTaskWithRequest:_request completionHandler:^(NSData *_data, NSURLResponse *_response, NSError *_error)
{
if (_error)
{
NSLog(#"Error %#",[_error description]);
}
else
{
NSLog(#"No Error %#",[[NSString alloc] initWithData:_data encoding:NSUTF8StringEncoding]);
}
}];
[_dataTask resume];
[_session finishTasksAndInvalidate];
It works Perfectly, I get output also. But when I run same code in Instrument I get following leaks Instrument Output

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];
}

Trying to understand asynchronous calls

I have this method
- (NSString*) createUserWithName:(NSString*)TheName
{
NSURL *URL =someUrlthatIncludesTheName
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"GET"];
NSURLSession *session = [NSURLSession sharedSession];
NSURL *URL = [NSURL URLWithString:url];
NSURLSessionTask *task = [session dataTaskWithURL:URL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (response) {
NSError* error = nil;
NSArray *output = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
myID = [[output objectAtIndex:0] objectForKey:#"UserID"];
}
}];
[task resume];
return myID;
}
and another method
-(void)doSomethingWith: (NSString*) anID
Somewhere in my code, I call these methods subsequently, like this:
[self createUserWithName:#"John"];
[self doSomethingWith:myID];
However, due to the fact that the NSURLSession in createUserWithName: is asynchronous, doSomethingWith: is fired with myID = (null).
What is the best way to approach this problem, without necessarily falling back to deprecated synchronous NSURLConnection?
Thanks in advance
The workflow is supposed to be
- (void)createUserWithName:(NSString*)TheName
{
NSURL *URL =someUrlthatIncludesTheName
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"GET"];
NSURLSession *session = [NSURLSession sharedSession];
NSURL *URL = [NSURL URLWithString:url];
NSURLSessionTask *task = [session dataTaskWithURL:URL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (response) {
NSError* error = nil;
NSArray *output = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
myID = [[output objectAtIndex:0] objectForKey:#"UserID"];
[self doSomethingWith:myID];
}
}];
[task resume];
}
And the call is just
[self createUserWithName:#"John"];
The method doSomethingWith: is asynchronously executed in the completion block.
Alternatively use a custom completion block
- (void)createUserWithName:(NSString *)theName completion:^(NSString *identifier)completion
{
NSURL *URL =someUrlthatIncludesTheName
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"GET"];
NSURLSession *session = [NSURLSession sharedSession];
NSURL *URL = [NSURL URLWithString:url];
NSURLSessionTask *task = [session dataTaskWithURL:URL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (response) {
NSError* error = nil;
NSArray *output = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
myID = [[output objectAtIndex:0] objectForKey:#"UserID"];
completion(myID);
}
}];
[task resume];
}
and call it with
[self createUserWithName:#"John" completion:^(NSString *identifier) {
[self doSomethingWith:identifier];
}];

how to handle response in json

I'm using this piece of code for hit data in url.
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://dev1.brainpulse.org/quickmanhelp/webservice/api.php?act=registration"];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request1 setHTTPMethod:#"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"company_name", _CompanyName.text,
#"email_id", _Email.text,#"password", _Password.text,nil];
NSLog(#"Result: %#",request1);
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request1 setHTTPBody:postData];
NSURLResponse *response = nil;
// NSError *error = nil;
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request1 completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Handle your response here
NSLog(#"Result: %#",mapData);
NSLog(#"Result: %#",request1);
NSLog(#"Result: %#",data);
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"Result: %#",dictionary);
NSLog(#"Result error : %#",error.description);
}];
[postDataTask resume];
value of uitextfield is not store in url when i clicked on button, what should i do here?
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://dev1.brainpulse.org/quickmanhelp/webservice/api.php?act=registration"];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request1 setHTTPMethod:#"POST"];
//NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: _CompanyName.text,#"company_name",
//_Email.text,#"email_id", _Password.text,#"password",nil];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"yyyyy",#"company_name",
#"karthik.saral#gmail.com",#"email_id", #"XXXXX",#"password",nil];
NSLog(#"Result: %#",request1);
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request1 setHTTPBody:postData];
NSURLResponse *response = nil;
// NSError *error = nil;
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request1 completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Handle your response here
NSLog(#"Result: %#",mapData);
NSLog(#"Result: %#",request1);
NSLog(#"Result: %#",data);
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"Result: %#",dictionary);
NSLog(#"Result error : %#",error.description);
NSLog(#"answewrv : %#",dictionary);
NSLog(#"Result error : %#",error.description);
}];
[postDataTask resume];
this is updated code after the amendments. i am getting the same error.
You are wrong here:
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"company_name", _CompanyName.text,
#"email_id", _Email.text,#"password", _Password.text,nil];
It should be
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: _CompanyName.text,#"company_name",
_Email.text,#"email_id", _Password.text,#"password",nil];
initWithObjectsAndKeys mean: object,key, object, key
I have done also this type work you can see this , may be it will help you.
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#" your URL "];
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=%#&password=%#&api_key=Your key", usernameField.text,passwordField.text];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSLog(#"%#", mapData);
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",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];
}
- (void)checkUserSuccessfulLogin:(id)json
{
// NSError *error;
NSDictionary *dictionary = (NSDictionary *)json;
if ([[dictionary allKeys] containsObject:#"login"])
{
if ([[dictionary objectForKey:#"login"] boolValue])
{
[self saveLoginFileToDocDir:dictionary];
ItemManagement *i = [[ItemManagement alloc]init];
[self presentViewController:i animated:YES completion:Nil];
}
else
{
NSLog(#"Unsuccessful, Try again.");
UIAlertView *alertLogin = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Wrong Username Or Password" delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:nil];
[alertLogin show];
}
}
}
- (void)saveLoginFileToDocDir:(NSDictionary *)dictionary
{
NSArray *pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:#"Login.plist"];
BOOL flag = [dictionary writeToFile:path atomically:true];
if (flag)
{
NSLog(#"Saved");
}
else
{
NSLog(#"Not Saved");
}
}

Resources