Not getting server response by using http post method & nsurlsession - ios

NSError *error;
NSDictionary *dicData = [[NSDictionary alloc]initWithObjectsAndKeys:username,#"username",password,#"password",cpassword,#"cpassword",mobile,#"mobile",firstname,#"firstname",lastname,#"lastname",#"register",#"action",nil];
NSLog(#"parameter=%#",dicData);
NSURLComponents *components = [NSURLComponents componentsWithString:#"http://followerlikes.com/app_appoint/json/?action=register"];
NSMutableArray *queryItems = [NSMutableArray array];
for (NSString *key in dicData) {
[queryItems addObject:[NSURLQueryItem queryItemWithName:key value:dicData[key]]];
}
components.queryItems = queryItems;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:components.URL];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSData *postData = [NSJSONSerialization dataWithJSONObject:dicData options:0 error:&error];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"%#",data);
NSLog(#"%#",response);
NSLog(#"%#",error);
NSString *strRes = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",strRes);
NSError *resultError;
NSDictionary *dicResult = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&resultError];
dispatch_async(dispatch_get_main_queue(), ^
{
if (error !=nil) {
NSLog(#"%#",error.description);
NSLog(#"%#",error.localizedDescription);
}
else {
completion(dicResult);
}
});
}];
[task resume];
}

In order send request for getting data, you have to add key in info.plist as follow :
And just update your code as below :
NSError *error;
NSDictionary *dicData = [[NSDictionary alloc] initWithObjectsAndKeys:#"user123", #"username", #"pass1234", #"password", #"pass1234", #"cpassword", #"0123456789", #"mobile", #"User", #"firstname", #"Name", #"lastname", #"register", #"action", nil];
NSLog(#"parameter=%#",dicData);
// NSURLComponents *components = [NSURLComponents componentsWithString:#"http://followerlikes.com/app_appoint/json/?action=register"];
//
// NSMutableArray *queryItems = [NSMutableArray array];
// for (NSString *key in dicData) {
// [queryItems addObject:[NSURLQueryItem queryItemWithName:key value:dicData[key]]];
// }
// components.queryItems = queryItems;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://followerlikes.com/app_appoint/json/?action=register"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSData *postData = [NSJSONSerialization dataWithJSONObject:dicData options:0 error:&error];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"Data : %#",data);
NSLog(#"RESPONSE : %#",response);
NSLog(#"ERROR : %#",error);
NSString *strRes = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",strRes);
NSError *resultError;
NSDictionary *dicResult = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&resultError];
NSLog(#"RESPONSE DICT : %#", dicResult);
dispatch_async(dispatch_get_main_queue(), ^ {
if (error !=nil) {
NSLog(#"ERROR : %#",error.description);
NSLog(#"ERROR : %#",error.localizedDescription);
}
else {
// completion(dicResult);
}
});
}];
[task resume];

Related

Postman gives a success response while the same API throws error when called through code

A POST API throws error when I call it in my code while gives a success response through postman. I use the same method to call other services and they work just fine. The problem is with this particular API. Here is the code I use for calling the API:
-(void)createNSUrlSessionLogin:(NSURL*)URL postDict:(NSDictionary*)dict successBlock:(completionBlock)completionBlock
failureBlock:(failureBlock)failure
{
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
NSData *postData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if ([data length] > 0 && error == nil)
{
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"result json: %#", jsonArray);
if (!jsonArray) {
failure(NO,nil);
}else
{
completionBlock(YES,jsonArray);
}
}
else if ([data length] == 0 && error == nil){
failure(NO,nil);
}
else if (error != nil){
NSLog(#"Error is %#",[error description]);
failure(NO,nil);
}
}];
[postDataTask resume];
}
Any help is appreciated.
I'm sorry, i'm cannot write comments. But I see, that you do content-type: url-encoded request via postman, and application-json via code. If API accept only url-encoded requests, this is your answer.
Try this...
-(void)serverRequestFetchData:(NSMutableURLRequest*)request withCallback:(void (^)(NSArray *, NSError *))aCallback {
NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
dispatch_sync(dispatch_get_main_queue(), ^{
NSHTTPURLResponse *statusResponse = (NSHTTPURLResponse *)response;
if (statusResponse.statusCode >= 200 && statusResponse.statusCode < 300) {
if (data.length > 0 && error == nil) {
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
if (aCallback) {
aCallback(array, nil);
}
} else {
aCallback(#[], error);
}
} else {
NSString *statusMessage = [NSString stringWithFormat:#"Invalid status response code: %ld", (unsigned long)statusResponse.statusCode];
NSError *statusError = [[NSError alloc] initWithDomain:#"com.somedomain" code:10001 userInfo:#{NSLocalizedDescriptionKey : NSLocalizedString(statusMessage, nil)}];
if (aCallback) {
aCallback(#[], statusError);
}
}
});
}];
[dataTask resume];
}
-(void)myRequest {
NSString *jsonRequest = [NSString stringWithFormat:#"{\"access_token\":\"ACCESS_TOKEN_HERE\"}"];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
NSString *URLString = [NSString stringWithFormat:#"YOUR_FIRST_URL_STRING"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URLString]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", (int)[requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
[self serverRequestFetchData:request withCallback:^(NSArray *array, NSError *error) {
}];
}

How to post string data to API

I wanted to post a string data to API, I try to send it to server by using the below code. I've check api there by using the postman, it did not pass in the string data into the server. I do not know what is the problem and need help on this.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:reqURLStr]];
[request setHTTPMethod:#"POST"];
**//Pass The String to server**
NSString *userUpdate =[NSString stringWithFormat:#"service_type=%#&ParcelSize=%#&ReceiverName=%#&MobileNumber=%#&Email=%#&DropOffHub=%#&PickupHub=%#" ,serviceType,pSize,rName,rMobile,rEmail,dropHubID,pickHubID];
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data1];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[data makeRestAPICall:reqURLStr] forHTTPHeaderField:#"Authorization"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(#"got response==%#", resSrt);
if(resSrt)
{
NSLog(#"got response");
}
else
{
NSLog(#"fail to connect");
}
return resSrt;
Simple answer
-(void)postJsonDataToServer{
NSDictionary *parameters = #{
#"service_type": serviceType,
#"ParcelSize": pSize,
#"ReceiverName": rName,
#"MobileNumber": rMobile,
#"Email" : rEmail,
#"DropOffHub" : dropHubID,
#"PickupHub" : pickHubID
};
NSData *data = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http:/api/order/add"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *dataTask = [session uploadTaskWithRequest: request
fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(data != nil)
{
NSError *parseError = nil;
//If the response is in dictionary format
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
//OR
//If the response is in array format
NSArray *res = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"The res is - %#",res);
}
else
NSLog(#"Data returned the parameter is nil here");
}];
[dataTask resume];
}

How to add Dictionary as a Request Parameter For HTTPBody in NSJSONSerialization?

I am creating one demo Web Services Code without using AFNetworking Framework.
My HTTP Request Parameter in Dictionary.
How can I set it on HTTPBody?
MY Code is as follow
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl];
[request setHTTPMethod:#"POST"];
NSString *postString = "Request Parameter";
[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];
You Can Do like that With AFnetworking and Without Af Networking.
NSString *stringUrl = #"xxx";
NSURLSessionConfiguration *myConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFHTTPSessionManager *myManager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:myConfiguration];
AFHTTPResponseSerializer *mySerilizer = [[AFHTTPResponseSerializer alloc]init];
[myManager setResponseSerializer:mySerilizer];
NSDictionary *param = [[NSDictionary alloc]initWithObjectsAndKeys:#"value==",#"Token", nil];
NSData *data = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:nil];
NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *requestParameter = [NSDictionary dictionaryWithObject:string forKey:#"request"];
[manager POST:stringUrl parameters:requestParameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSError *error;
if(!error)
{
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
NSLog(#"%#",dict);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
Without Dictionary
NSString *urlString = #"xxxx";
// Do any additional setup after loading the view, typically from a nib.
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:configuration];
AFHTTPResponseSerializer *serilizer = [[AFHTTPResponseSerializer alloc]init];
[manager setResponseSerializer:serilizer];
NSDictionary *dict = [[NSDictionary alloc]initWithObjectsAndKeys:#"value",#"key", nil];
[manager POST:urlString parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSError *error;
if(!error)
{
NSDictionary *finalData = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
NSLog(#"Final Data is %#",finalData);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
Without AFNetworking
NSString *MyUrlString = #"xxxx";
NSURL *url = [NSURL URLWithString:MyUrlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSString *postString = #"key=value";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSError *jsonError;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&jsonError];
NSLog(#"requestReply: %#", json);
}] resume];
Note:-Do not forget to put resume
Thank you
Check your condition with my working code,
NSMutableURLRequest *_request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:50.0];
[_request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"]; // Interact your backend developer for header
[_request addValue:#"application/json" forHTTPHeaderField:#"Accept"];// Interact your backend developer for header
[_request setHTTPMethod:#"POST"];
NSError *error;
NSData *_inputData = [NSJSONSerialization dataWithJSONObject:inputDictionary options:0 error:&error];
[_request setHTTPBody:_inputData];
NSURLSessionDataTask *_fetchData = [[[self class] session] dataTaskWithRequest:_request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(!error) {
NSError* error;
completionBlock(data,error,1);
} else {
completionBlock(data,error,0);
}
}];
[_fetchData resume];
Got The Data
NSURL *stringwithUrl = [NSURL URLWithString:#"XXXX"];
NSMutableURLRequest *requestUrl = [NSMutableURLRequest requestWithURL:stringwithUrl];
[requestUrl setHTTPMethod:#"POST"];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:#"Value==",#"Key", nil];
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString *mainString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSString *requestString = #"request=";
NSString *finalString = [requestString stringByAppendingString:mainString];
[requestUrl setHTTPBody:[finalString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *sesion = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[sesion dataTaskWithRequest:requestUrl completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"%#",dict);
}]resume];

How to Post JSON Data in synchronously way?

How to post JSON Data in synchronously way? Can use NSURLSession or AFNetworking or other way?
Sample basic code for posting data to server using synchronous
//PASS YOUR URL HERE
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"your URL"]];
//create the Method "POST" for posting data to server
[request setHTTPMethod:#"POST"];
//Pass The String to server like below
NSString *strParameters =[NSString strin gWithFormat:#"user_email=%#&user_login=%#&user_pass=%#& last_upd_by=%#&user_registered=%#&",txtemail.text,txtuser1.text,txtpass1.text,txtuser1.text,datestr,nil];
//Print the data that what we send to server
NSLog(#"the parameters are =%#", strParameters);
//Convert the String to Data
NSData *data1 = [strParameters dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
//This is for Response
NSLog(#"got response==%#", resSrt);
if(resSrt)
{
NSLog(#"got response");
}
else
{
NSLog(#"faield to connect");
}
In user3182143's answer, sendSynchronousRequest is deprecated in latest version iOS 9.
You can use NSURLSession
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:londonWeatherUrl]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
NSString *strResult = [[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];
}] resume];
Here is my solution:
- (IBAction)postJSONSynchronization:(id)sender {
__block BOOL success = NO;
__block NSDictionary *jsonDic = nil;
NSURLSession *session = [NSURLSession sharedSession];
// 创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url]];
request.HTTPMethod = #"POST"; // 请求方法
NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
[parameters setObject:#13577766655 forKey:#"phoneNumber"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
request.HTTPBody = jsonData; // 请求体
NSCondition *condition = [[NSCondition alloc] init];
// 创建任务
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"Child Thread:%#",[NSThread currentThread]);
if (!error) {
jsonDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
success = YES;
} else {
NSLog(#"%#",error);
}
[condition lock];
[condition signal];
[condition unlock];
}];
[task resume];
// 启动任务
NSLog(#"Main Thread:%#",[NSThread currentThread]);
[condition lock];
[condition wait];
[condition unlock];
NSLog(#"测试时机");
NSLog(#"josnDic:%#",jsonDic);}

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