I have a NSString which contains the URL. I want to make a GET request using the URL and also check if the response is 200.
With the current code i get response as 0.
Here is my code:
NSString *Url = #"http://www.xyx.com";
NSData *data = [Url dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *len = [NSString stringWithFormat:#"%lu", (unsigned long)[data length]];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc]init];
[req setURL:[NSURL URLWithString:Url]];
[req setHTTPMethod:#"GET"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:req completionHandler:^(NSData data, NSURLResponse response, NSError *error) {
NSString *req = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"Reply = %#", req);
}]resume];
use this code it works for you:
-(void)yourMethodNAme
{
NSString *post = #"";
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:#"Your URL"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
//NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
//NSLog(#"str : %#",dict6);
}
- (id)cleanJsonToObject:(id)data
{
NSError* error;
if (data == (id)[NSNull null])
{
return [[NSObject alloc] init];
}
id jsonObject;
if ([data isKindOfClass:[NSData class]])
{
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
}
else
{
jsonObject = data;
}
if ([jsonObject isKindOfClass:[NSArray class]])
{
NSMutableArray *array = [jsonObject mutableCopy];
for (int i = (int)array.count-1; i >= 0; i--)
{
id a = array[i];
if (a == (id)[NSNull null])
{
[array removeObjectAtIndex:i];
} else
{
array[i] = [self cleanJsonToObject:a];
}
}
return array;
}
else if ([jsonObject isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *dictionary = [jsonObject mutableCopy];
for(NSString *key in [dictionary allKeys])
{
id d = dictionary[key];
if (d == (id)[NSNull null])
{
dictionary[key] = #"";
} else
{
dictionary[key] = [self cleanJsonToObject:d];
}
}
return dictionary;
}
else
{
return jsonObject;
}
}
and finally call it in ViewDidLoad as [self yourMethodNAme];
-(void) httpGetWithCustomDelegateWithString: (NSString*)urlString
{
[self startActivity];
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSURL *url = [NSURL URLWithString:urlString];
NSURLSessionDataTask *dataTask =[defaultSession dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSLog(#"Response:%# %#\n", response, error);
if(error == nil)
{
//NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
//NSLog(#"Data = %#",text);
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
deserializedDictionary = nil;
if (jsonObject != nil && error == nil)
{
if ([jsonObject isKindOfClass:[NSDictionary class]])
{
//Convert the NSData to NSDictionary in this final step
deserializedDictionary = (NSDictionary *)jsonObject;
NSLog(#"dictionary : %#",deserializedDictionary);
}
if ([jsonObject isKindOfClass:[NSArray class]])
{
deserializedArr = (NSArray*)jsonObject;
NSLog(#"array : %#",deserializedArr);
}
}
[self setAlert];
}
else
{
[activityView removeFromSuperview];
[[UIApplication sharedApplication] endIgnoringInteractionEvents];
[self showAlert:#"Error" :#"Network error occured." :#"Ok"];
}
}];
[dataTask resume];
}
just use the above code and call it by
[self httpGetWithCustomDelegateWithString:#"webStringHere"];
On Completion, it will call the method -(void)setAlert; so declare it in your class where you use this.
This may be due to App Transport Security blocking HTTP.
App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.
Try making a request to a secure site (e.g. https://www.google.com) as a test.
Related
I have to send the array as one of the parameter to the url using get request the url is http://13.229.45.226/api/resource/Employee/?filters=[["Employee", "company_email", "=", "susee#lektrify.club"]] . and i am using nsurl sessions for api calling.
please find the below code
NSArray *myArray = #[#"Employee",#"company_email",#"=",Emailid];
NSData *json = [NSJSONSerialization dataWithJSONObject:myArray options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
NSString *urlstr= [NSString stringWithFormat:#"http://xx.xxx.xx.xxx/api/resource/Employee/?filters=[\n%#]",jsonString];
NSLog(#"%#",urlstr);
[apicall getDictionaryFromApiwithoutlogin:urlstr restfulType:kRestfulGet andUseContentType:NO withRequestBody:nil withheader:YES completionHandler:^(NSDictionary *result){
dispatch_async(dispatch_get_main_queue(), ^{ }];
this is the code written for the universal api calling in foe i am giving inputs.
-(void)getDictionaryFromApiwithoutlogin:(NSString *)url restfulType:(NSInteger)restfulType andUseContentType:(BOOL)useContentType withRequestBody:(NSData*)httpBody withheader:(BOOL)header completionHandler:(void (^)(NSDictionary *isSuccess))isSuccess
{
loginstatus = [[NSUserDefaults standardUserDefaults] boolForKey:#"loginStatus"];
if (![APICall hasNetwork])
{
// [customBezelActivityView removeViewAnimated:YES];
// [Util displayToastMessage:#"No internet connection"];
return;
}
/* RESTFUL request function, all API request will come here */
//url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
url=[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"url:%#",url);
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:300.0];
// set request variables
if (restfulType == kRestfulGet) {
[request setHTTPMethod:#"GET"];
} else if (restfulType == kRestfulPost) {
[request setHTTPMethod:#"POST"];
} else if (restfulType == kRestfulPut) {
[request setHTTPMethod:#"PUT"];
} else {
[request setHTTPMethod:#"DELETE"];
}
if (useContentType) {
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
}
if (header) {
[request setValue:[NSString stringWithFormat:#"Bearer %#",[[NSUserDefaults standardUserDefaults]valueForKey:#"access_token"]] forHTTPHeaderField:#"Authorization"];
}
if (httpBody != nil) {
request.HTTPBody = httpBody;
}
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error == nil)
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if ([httpResponse respondsToSelector:#selector(statusCode)])
{
NSInteger responseStatusCode = [httpResponse statusCode];
NSLog(#"api response: %#", httpResponse);
if (responseStatusCode == 200)
{
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
isSuccess(response);
}else if (responseStatusCode==401)
{
dispatch_async(dispatch_get_main_queue(), ^{
[customBezelActivityView removeViewAnimated:YES];
[APICall sigininpageafteraccestokenexperise];
});
}
else if (responseStatusCode==500)
{
dispatch_async(dispatch_get_main_queue(), ^{
[customBezelActivityView removeViewAnimated:YES];
[[NSNotificationCenter defaultCenter]postNotificationName:#"usernotfound" object:nil];
});
}
else{
[customBezelActivityView removeViewAnimated:YES];
[APICall handleApiErrorCode:responseStatusCode];
}
}
}else
dispatch_async(dispatch_get_main_queue(), ^{
[customBezelActivityView removeViewAnimated:YES];
[Util handleErrorCodesForApi:(int)error.code];
});
}];
[postDataTask resume];
[session finishTasksAndInvalidate];
}
When i try in post man array link this [["Employee", "company_email", "=", "xxx#xxx.club"]] . it is working how to for this array and add to url and make get request.
thanks for quick response.
I found the solution to my question
the solution is you have to create an array,you have to NSJSONSerialization to data and to encoded string this solves the issue
NSArray *myArray = #[#"Employee",#"company_email",#"=",Emailid];
NSData *json = [NSJSONSerialization dataWithJSONObject:myArray options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
NSString *urlstr= [NSString stringWithFormat:#"http://xx.xxx.xx.xxx/api/resource/Employee/?filters=[\n%#]",jsonString];
please check the updated question for full answer
You can use NSURLComponents class to construct URL from their constituent parts.
In your answer you are constructing queryString manually by self, it is ok with one parameter, but if you have multiple parameters then it will got hectic.
for your example:
NSURLComponents *urlComponents = [NSURLComponents componentsWithString:#"http://13.229.45.226/api/resource/Employee/"];
NSURLQueryItem *item1 = [NSURLQueryItem queryItemWithName:#"filters" value:#"Employee"];
NSURLQueryItem *item2 = [NSURLQueryItem queryItemWithName:#"company_email" value:#"susee#lektrify.club"];
[urlComponents setQueryItems: #[item1,item2]];
NSLog(#"%#",urlComponents.URL);
Output:
http://13.229.45.226/api/resource/Employee/?filters=Employee&company_email=susee#lektrify.club
I am trying to upload a UIImage to .Net server by converting the image into base 64 and NSData. But I am getting the response null. Here is my code.
NSString *base64Encoded = [imageData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
NSString *post= [NSString stringWithFormat:#"myServerSideUrl?Image=%#",base64Encoded];
NSLog(#"PostData: %#",post);
NSString* webStringURL = [post stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
NSURL* url = [NSURL URLWithString:webStringURL];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSData *responseData = [[NSData alloc]initWithData:urlData];
if ([response statusCode] >=200 )
{
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData: responseData options:0 error:nil];
NSLog(#"%#",jsonData);
}
After some time, I just checked in postman showing like url too long HttpResponseCode:414. Also I tried to send the image in NSData format using AFNetwork, getting the same response. And I just googled about this, saying like send the base 64 string in body. When I tried to send image in body, server side can't get the image. They are creating the API like GET method but the actual method is POST. Is there any other solution about this. Any suggestions.
You are setting NSData to your request body without defining any key-value pair.
Try this code using AFNetworking...
- (void) uploadFileRequestWithHttpHeaders:(NSMutableDictionary*) headers
withServiceName:(NSString*) serviceName
withParameters:(NSMutableDictionary*) params
withFileData:(NSArray*) files
{
NSString *serviceUrl = [httpBaseURL stringByAppendingPathComponent:serviceName];
if (headers == nil)
{
NSDictionary *headers = [[NSDictionary alloc] initWithObjectsAndKeys:#"multipart/form-data",#"Content-Type",nil];
[self setHeaders:headers];
}
else
{
[headers setObject:#"multipart/form-data" forKey:#"Content-Type"];
[self setHeaders:headers];
}
[httpSessionManager POST:serviceUrl
parameters:params
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
for (NSData *fileData in files)
{
[formData appendPartWithFileData:fileData name:#"userProfileImg" fileName:#"profile_pic.jpg" mimeType:#"image/jpeg"];
}
}
success:^(NSURLSessionDataTask *task, id responseObject) {
if (success != nil)
}
failure:^(NSURLSessionDataTask *task, NSError *error) {
if (failure != nil)
}];
}
- (void) setHeaders:(NSDictionary*) headers
{
if (headers != nil)
{
NSArray *allHeaders = [headers allKeys];
for (NSString *key in allHeaders)
{
[httpSessionManager.requestSerializer setValue:[headers objectForKey:key] forHTTPHeaderField:key];
}
}
}
- (void) addQueryStringWithParams:(NSDictionary*) params
{
[httpSessionManager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error) {
__block NSMutableString *query = [NSMutableString stringWithString:#""];
NSError *err;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&err];
NSMutableString *jsonString = [[NSMutableString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
query = jsonString;
return query;
}];
}
And call this method like this..
NSArray *objects = [NSArray arrayWithObjects:#"multipart/form-data",#"1.0",#"ios",token, nil];
NSArray *Keys = [NSArray arrayWithObjects:#"content-type",#"version",#"os",#"token", nil];
NSMutableDictionary *headers = [[NSMutableDictionary alloc]initWithObjects:objects forKeys:Keys];
NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
[paraDic setObject:self.userNameField.text forKey:#"name"];
NSData * userProfileImg = UIImageJPEGRepresentation(image, 0.8f);
imageDataArray = [NSArray arrayWithObjects:userProfileImg, nil];
[self uploadFileRequestWithHttpHeaders:headers withServiceName:#"updateProfile" withParameters:params withFileData:files];
You can try this code using NSURLSession-
- (void)postRequestForSubmitDataToServer {
//Put your action URL
NSURL *aUrl = [NSURL URLWithString:#"action_url.php?&attachment=att&submit=submit"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil) {
//change JSON type according to ur need.
NSArray *JSON = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
NSLog(#"Data = %#",JSON);
} else {
NSLog(#"%#", error);
}
}];
[postDataTask resume];
}
My form data-
<form action="action_url.php" method="post" enctype="multipart/form-data">
Your Photo: <input type="file" name="attachment" size="25" /><br>
<input type="submit" name="submit" value="Submit" /> </form>
Firstly I have two text fields first is login and second is password and one login button. I am using a storyboard and login button connected to another view controller by push segue. This time working in my project, Put username and password in textfield and select login button and print server response in console.
I want to login successfully after move another view and login is failed don't move another view.
My php code
<?php
header('Content-type: application/json');
include('../conn.php');
if($_POST)
{
$loginid = $_POST['loginid'];
$loginpassword = $_POST['loginpassword'];
$schoolid = substr_id($loginid);
$table = tb3($schoolid);//profile
$sql=mysql_query("select * from $table where ID = '".$loginid."' AND PASSWORD = '".$loginpassword."'",$conn);
$row=mysql_fetch_assoc($sql);
if(mysql_num_rows($sql)>0)
{
echo '{"success":1}';
}
else
{
echo '{"success":0,"error_message":"UserID and/or password is invalid."}';
}
}
else
{
echo '{"success":0,"error_message":"UserID and/or password is invalid."}';
}
My viewcontroller code
- (IBAction)Login:(id)sender {
if([[self.user_id text] isEqualToString:#""] || [[self.password text] isEqualToString:#""] ) {
} else {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://sixthsenseit.com/school/project/ios/login.php"]];
//create the Method "GET" or "POST"
[request setHTTPMethod:#"POST"];
//Pass The String to server(YOU SHOULD GIVE YOUR PARAMETERS INSTEAD OF MY PARAMETERS)
NSString *userUpdate =[NSString stringWithFormat:#"loginid=%#&loginpassword=%#&",_user_id.text,_password.text, nil];
//Check The Value what we passed
NSLog(#"the data Details is =%#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate 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");
}
}
}
This line is wrong
NSString *userUpdate =[NSString stringWithFormat:#"loginid=%#&loginpassword=%#&",_user_id.text,_password.text, nil];
you are additionally added the & in your params ,this is not in loginpassword=%#& , you need to call like loginpassword=%# remove and send the request
use like
NSString *userUpdate =[NSString stringWithFormat:#"loginid=%#&loginpassword=%#",_user_id.text,_password.text, nil];
The problem is you are not serlize your JSON
so remove this line in your NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
and I follow your Answer
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %ld", (long)[response statusCode]);
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSError *error = nil;
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:urlData
options:NSJSONReadingMutableContainers
error:&error];
int success = [jsonData[#"success"] integerValue];
if(success == 1)
{
NSLog(#"Login SUCCESS");
[self performSegueWithIdentifier:#"login_success" sender:self];
} else {
NSString *error_msg = (NSString *) jsonData[#"error_message"];
[self alertStatus:error_msg :#"Sign in Failed!" :0];
}
}
Ankur kumawat I tried your coding and Brother #Anbu.karthik answer in iOS 9.I got few warnings.First I post Anbu.Karthik brother answer.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://sixthsenseit.com/school/project/ios/login.php"]];
//create the Method "GET" or "POST"
[request setHTTPMethod:#"POST"];
//Pass The String to server(YOU SHOULD GIVE YOUR PARAMETERS INSTEAD OF MY PARAMETERS)
NSString *strUserId = #"1000710017";
NSString *strPassword = #"XM0MB";
NSString *userUpdate =[NSString stringWithFormat:#"loginid=%#&loginpassword=%#",strUserId,strPassword, nil];
//Check The Value what we passed
NSLog(#"the data Details is =%#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate 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];
NSError *error = nil;
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:responseData
options:NSJSONReadingMutableContainers
error:&error];
int success = [jsonData[#"success"] integerValue];
if(success == 1)
{
NSLog(#"Login SUCCESS");
[self performSegueWithIdentifier:#"login_success" sender:self];
} else {
NSString *error_msg = (NSString *) jsonData[#"error_message"];
[self alertStatus:error_msg :#"Sign in Failed!" :0];
}
Above is brother Anbu.Karthik answer.I tried that and it shows me the warnings.
Warnings are
'sendSynchronousRequest:returningResponse:error:' is deprecated: first
deprecated in iOS 9.0 - Use [NSURLSession
dataTaskWithRequest:completionHandler:] (see NSURLSession.h
Then
Implicit conversion loses integer precision: 'long _Nullable' to 'int'
As I get warning I want to remove warning and
I must use
NSURLSession with dataTask because sendSynchronousRequest:returningResponse:error:' is deprecated in iOS 9.0
Then I modified the code.
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://sixthsenseit.com/school/project/ios/login.php"]];
NSString *strUserId = #"1000710017";
NSString *strPassword = #"XM0MB";
NSString *userUpdate =[NSString stringWithFormat:#"loginid=%#&loginpassword=%#",strUserId,strPassword, nil];
//create the Method "GET" or "POST"
[urlRequest setHTTPMethod:#"POST"];
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[urlRequest setHTTPBody:data1];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if(httpResponse.statusCode == 200)
{
NSError *parseError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"The response is - %#",responseDictionary);
NSInteger success = [[responseDictionary objectForKey:#"success"] integerValue];
if(success == 1)
{
NSLog(#"Login SUCCESS");
}
else
{
NSLog(#"Login FAILURE");
}
}
else
{
NSLog(#"Error");
}
}];
[dataTask resume];
The printed result is
The response is - {
success = 1;
}
And
Login SUCCESS
Now above my code works perfectly:-)
Try this code in view Controller file:
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSLog(#"%#",dict);
if (dict)
{
NSString *status = [NSString stringWithFormat:#"%#",[dict valueForKey:#"success"]];
}
output: 1 // successfully
or
0 // Unsccssfully
NSString *msg = [NSString stringWithFormat:#"%#",[dict valueForKey:#"error_message"]];
Replace your code with this :
- (IBAction)Login:(id)sender {
if([[self.user_id text] isEqualToString:#""] || [[self.password text] isEqualToString:#""] ) {
} else {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://sixthsenseit.com/school/project/ios/login.php"]];
//create the Method "GET" or "POST"
[request setHTTPMethod:#"POST"];
//Pass The String to server(YOU SHOULD GIVE YOUR PARAMETERS INSTEAD OF MY PARAMETERS)
NSString *userUpdate =[NSString stringWithFormat:#"loginid=%#&loginpassword=%#&",_user_id.text,_password.text, nil];
//Check The Value what we passed
NSLog(#"the data Details is =%#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate 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];
Dictionary *dictResponce = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
if (dictResponce)
{
NSString *status = [NSString stringWithFormat:#"%#",[dict valueForKey:#"success"]];
if (status == "1"){
//Push to home view controller
[self performSegueWithIdentifier:#"Home_page" sender:self];
}
else{
NSLog([NSString stringWithFormat:#"%#",[dict valueForKey:#"error_message"]]);
}
}
else{
NSLog(#"faield to connect");
}
}
}
In my project i am passing this API: http://dev-demo.info.bh-in-15.webhostbox.net/dv/nationalblack/api/businessbysubcat with params: prod_id=25,var_id=140.
The problem is when i am pass this api in Rest Client it displays correct response but when i am trying to put it in my code it shows different response.
i am using the following code:
-(void)listofNotice
{
NSString *post = [NSString stringWithFormat:#"prod_id=25,var_id=140"];
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://dev-demo.info.bh-in-15.webhostbox.net/dv/nationalblack/api/businessbysubcat"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
//NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6);
}
- (id)cleanJsonToObject:(id)data
{
NSError* error;
if (data == (id)[NSNull null])
{
return [[NSObject alloc] init];
}
id jsonObject;
if ([data isKindOfClass:[NSData class]])
{
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
}
else
{
jsonObject = data;
}
if ([jsonObject isKindOfClass:[NSArray class]])
{
NSMutableArray *array = [jsonObject mutableCopy];
for (int i = (int)array.count-1; i >= 0; i--)
{
id a = array[i];
if (a == (id)[NSNull null])
{
[array removeObjectAtIndex:i];
} else
{
array[i] = [self cleanJsonToObject:a];
}
}
return array;
}
else if ([jsonObject isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *dictionary = [jsonObject mutableCopy];
for(NSString *key in [dictionary allKeys])
{
id d = dictionary[key];
if (d == (id)[NSNull null])
{
dictionary[key] = #"";
} else
{
dictionary[key] = [self cleanJsonToObject:d];
}
}
return dictionary;
}
else
{
return jsonObject;
}
}
it display the following response:
str : {
business = 0;
"business-list" = "Business list empty.";
response = 401;
}
but the actual response is something like this
please help me.. Thanks In advance
Please change this
NSString *post = [NSString stringWithFormat:#"prod_id=25,var_id=140"];
To:
NSString * post =[NSString stringWithFormat:#"prod_id=25&var_id=140"];
if possible use this:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.HTTPAdditionalHeaders = #{#"application/x-www-form-urlencoded" : #"Content-Type"};
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://dev-demo.info.bh-in-15.webhostbox.net/dv/nationalblack/api/businessbysubcat"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [post dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (data != nil){
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSInteger code = [httpResponse statusCode];
NSLog(#"Status Code: %ld", (long)code);
if (code == 200) {
NSError *error;
id responseObject =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
}
}
}];
[postDataTask resume];
OR
NSString *postString = [NSString stringWithFormat:#"prod_id=%#&var_id=%#",#"25",#"140"];
NSURL *urlPath = [NSURL URLWithString:#"http://dev-demo.info.bh-in-15.webhostbox.net/dv/nationalblack/api/businessbysubcat"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlPath
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
NSData *requestData = [postString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
[APP_DELEGATE removeLoader];
if(data != nil) {
NSDictionary *responseObject =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(#" %#", responseObject);
}
else {
}
}];
Hope this helps.
I think you need to change below code
NSString *post = [NSString stringWithFormat:#"prod_id=25,var_id=140"];
to
NSDictionary *prodDict=#{#"prod_id":#"25",
#"var_id":#"140"};
Hi i am very new for ios and in my project i am using NSUrlSession for calling services
but in my below code i have maintain if and else conditions for handing server response but those if and else conditions not calling
please help me where was the mistack happand?
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:myurl here]];
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"GET"];
[request setHTTPBody:[self httpBodyForParamsDictionary:params]];
//You now can initiate the request with NSURLSession or NSURLConnection, however you prefer. For example, with NSURLSession, you might do:
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"dataTaskWithRequest error: %#", error);
NSString * BasicnetworkError = [error localizedDescription];
NSString * AppendString = #"Http Response failed with the following ";
NSString * networkError = [AppendString stringByAppendingString:BasicnetworkError];
[self BasicError1:networkError];
}
else if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200) {
NSLog(#"Expected responseCode == 200; received %ld", (long)statusCode);
NSString *statusCodeError = [NSString stringWithFormat: #"Http Response failed with the following code %ld", (long)statusCode];
[self BasicError1:statusCodeError];
}
}
// If response was JSON (hopefully you designed web service that returns JSON!),
// you might parse it like so:
else{
NSError *parseError;
id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"else condtion");
if (!responseObject) {
NSLog(#"JSON parse error: %#", parseError);
} else {
NSLog(#"responseObject = %#", responseObject);
[self MainService:responseObject];
}
//if response was text/html, you might convert it to a string like so:
// ---------------------------------
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"final responseString = %#", responseString);
}
}];
[task resume];
}
- (NSData *)httpBodyForParamsDictionary:(NSDictionary *)paramDictionary{
NSMutableArray *parameterArray = [NSMutableArray array];
[paramDictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
NSString *param = [NSString stringWithFormat:#"%#=%#", key, [self percentEscapeString:obj]];
[parameterArray addObject:param];
}];
NSString *string = [parameterArray componentsJoinedByString:#"&"];
return [string dataUsingEncoding:NSUTF8StringEncoding];
}
- (NSString *)percentEscapeString:(NSString *)string{
NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)string,
(CFStringRef)#" ",
(CFStringRef)#":/?#!$&'()*+,;=",
kCFStringEncodingUTF8));
return [result stringByReplacingOccurrencesOfString:#" " withString:#"+"];
}
There was a case of wrong if else block mentioned in your code. please use below code.
- (void)viewDidLoad {
[super viewDidLoad];
NSDictionary *mainDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"COLLECTION",#"SearchBy",
#"1284",#"SearchKey",
#"",#"Color",
#"",#"PriceFrom",
#"",#"PriceTo",
#"",#"QtyFrom",
#"",#"QtyTo",
nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://203.77.214.78/StockManager/SL/SearchProducts"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[self httpBodyForParamsDictionary:mainDictionary]];
//You now can initiate the request with NSURLSession or NSURLConnection, however you prefer. For example, with NSURLSession, you might do:
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"dataTaskWithRequest error: %#", error);
}
else if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200) {
NSLog(#"Expected responseCode == 200; received %ld", (long)statusCode);
}else{
NSError *parseError;
id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"else condtion");
if (!responseObject) {
NSLog(#"JSON parse error: %#", parseError);
} else {
NSLog(#"responseObject = %#", responseObject);
}
//if response was text/html, you might convert it to a string like so:
// ---------------------------------
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"final responseString = %#", responseString);
}
}
}];
[task resume];
}