Here's the method that's giving me an error when I compile (see the requestMainPage method)
- (void)loginToMistarWithPin:(NSString *)pin password:(NSString *)password success:(void (^)(void))successHandler failure:(void (^)(void))failureHandler {
NSURL *url = [NSURL URLWithString:#"https://mistar.oakland.k12.mi.us/novi/StudentPortal/Home/Login"];
//Create and send request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
NSString *postString = [NSString stringWithFormat:#"Pin=%#&Password=%#",
[self percentEscapeString:pin],
[self percentEscapeString:password]];
NSData * postBody = [postString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:postBody];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse
*response, NSData *data, NSError *error)
{
// do whatever with the data...and errors
if ([data length] > 0 && error == nil) {
NSError *parseError;
NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (responseJSON) {
// the response was JSON and we successfully decoded it
NSLog(#"Response was = %#", responseJSON);
// assuming you validated that everything was successful, call the success block
if (successHandler)
successHandler();
} else {
// the response was not JSON, so let's see what it was so we can diagnose the issue
NSString *loggedInPage = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response was not JSON (from login), it was = %#", loggedInPage);
if (failureHandler)
failureHandler();
}
}
else {
NSLog(#"error: %#", error);
if (failureHandler)
failureHandler();
}
}]; }
- (NSData *)requestMainPage {
NSData *returner;
//Now redirect to assignments page
NSURL *homeURL = [NSURL URLWithString:#"https://mistar.oakland.k12.mi.us/novi/StudentPortal/Home/PortalMainPage"];
NSMutableURLRequest *requestHome = [[NSMutableURLRequest alloc] initWithURL:homeURL];
[requestHome setHTTPMethod:#"GET"]; // this looks like GET request, not POST
[NSURLConnection sendAsynchronousRequest:requestHome queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *homeResponse, NSData *homeData, NSError *homeError) //Error is in this line.
{
// do whatever with the data...and errors
if ([homeData length] > 0 && homeError == nil) {
NSError *parseError;
NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:homeData options:0 error:&parseError];
if (responseJSON) {
// the response was JSON and we successfully decoded it
NSLog(#"Response was = %#", responseJSON);
} else {
// the response was not JSON, so let's see what it was so we can diagnose the issue
NSString *homePage = [[NSString alloc] initWithData:homeData encoding:NSUTF8StringEncoding];
NSLog(#"Response was not JSON (from home), it was = %#", homePage);
return homePage;
}
}
else {
NSLog(#"error: %#", homeError);
}
return [NSString stringWithFormat:#"%#", homeData];
}]; }
The error came up when I decided I wanted my method (requestMainPage) to have a return type of NSData * rather then just returning void.
So I'm not sure exactly where the problem is.
I figured out my mistake, you can't return values from inside a block.
So if I remove the return homeError and return [NSString stringWithFormat:#"%#", homeData];, the problems go away and I can compile
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
Below is the code. It's using GET method for parsing and request.
- (void)getStudentsWithOptions:(NSString*)getURLString screen:(NSString *)screenString completion:(SkoolBeepCompletion)completion {
if (!completion) return;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:getURLString]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
completion(nil, error);
} else {
NSError *err = nil;
NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
//NSLog(#"dataDict : %#", dataDict);
if (!err) {
if ([screenString isEqualToString:#"My Students"]) {
[CoreDataController deleteAllObjects:#"Students"];
NSDictionary *dicEntry = [dataDict objectForKey:#"return_arr"];
for (NSDictionary *dicInsert in dicEntry) {
[CoreDataController storeStudentsObjects:dicInsert];
[CoreDataController storeChildrenObjects:dicInsert];
}
completion(dataDict, nil);
} else if ([screenString isEqualToString:#"User Settings"]) {
[CoreDataController deleteAllObjects:#"Profile"];
[CoreDataController storeProfileObjects:dataDict];
completion(dataDict, nil);
} else if ([screenString isEqualToString:#"About"]) {
[CoreDataController deleteAllObjects:#"About"];
[CoreDataController storeAboutObjects:dataDict];
completion(dataDict, nil);
} else if ([screenString isEqualToString:#"Works"]) {
[CoreDataController deleteAllObjects:#"Works"];
[CoreDataController storeWorksObjects:dataDict];
completion(dataDict, nil);
} else {
completion(dataDict, nil);
}
} else {
completion(nil, err);
}
}
}];
}
Above is line of code that I want in POST.
URLRequest must be using POST type.
I have added the code in my question.
Use NSMutableURLRequest for POST
NSString *Post=[NSString stringWithFormat:#"email=%#&password=%#",#"iamiosguy#gmail.com",#"lovetocode"];
NSData *PostData = [Post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *PostLengh=[NSString stringWithFormat:#"%d",[Post length]];
NSURL *Url=[NSURL URLWithString: #"Your URL"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:Url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setValue:PostLengh forHTTPHeaderField:#"Content-Lenght"];
[request setHTTPBody:PostData];
NSData *ReturnData =[NSURLConnection sendSynchronousRequest:request returningResponse:Nil error:Nil];
NSString *Response = [[NSString alloc] initWithData:ReturnData encoding:NSUTF8StringEncoding];
NSLog(#"Response%#",Response);
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");
}
}
}
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];
}
I am trying to fetch json data from local host. I have done this so many times. But this time it is not fetching data.
Json data
{
"swimming_pool":"0",
"security":"0",
"lift":"0",
"gym":"0",
"reserved_parking":"0",
"visitor_parking":"0",
"power_backup":"0",
"servant_room":"0",
"tennis_court":"0",
"rainwater_harvesting":"0",
"waste_management":"0",
"club_house":"0",
"desc":"Dkkd",
"city":"City",
"pincode":"Pin Co",
"locality":"locality",
"no_of_beds":"1",
"no_of_baths":"4"
}
Client side code
{
NSString *selectQuery=[NSString stringWithFormat:#"http://localhost/FilterQuery.php?swimming_pool=%li&&security=%li&&lift=%li&&gym=%li&&visitor_parking=%li&&power_backup=%li&&servant_room=%li&&rainwater_harvesting=%li&&waste_management=%li&&clubhouse=%li&&Posdesc=%#&&no_of_baths=%li&&no_of_beds=%li&&pincode=%li&&locality=%#&&protypedesc=%#",(long)swimpoolb,(long)securityb,(long)liftb,(long)gymb,(long)visparkingb,(long)pbu,(long)servantroom,(long)rainwaterh,(long)wastemanagement,(long)clubHouse,possesion,(long)bathrooms,(long)bedrooms,(long)zipcode,locality,propertyType];
NSString *newInsrStr = [selectQuery stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *dataaa=[NSData dataWithContentsOfURL:[NSURL URLWithString:newInsrStr]];
NSString *rr=[[NSString alloc]initWithData:dataaa encoding:NSUTF8StringEncoding];
NSLog(#"%#",rr);
jsondataa=[NSJSONSerialization JSONObjectWithData:dataaa options:0 error:nil];
//jsondataa is dictionary
swimmingPool=#"";
swimmingPool=[jsondataa objectForKey:#"swimming_pool"];
security=#"";
security=[jsondataa objectForKey:#"security"];
lift=#"";
lift=[jsondataa objectForKey:#"lift"];
gym=#"";
gym=[jsondataa objectForKey:#"gym"];
reserved_parking=#"";
reserved_parking=[jsondataa objectForKey:#"reserved_parking"];
visitor_parking=#"";
visitor_parking=[jsondataa objectForKey:#"visitor_parking"];
power_backUp=#"";
power_backUp=[jsondataa objectForKey:#"power_backup"];
NSLog(#"%#,%#,%#,%#,%#,%#,%#",swimmingPool,security,lift,gym,reserved_parking,visitor_parking,power_backUp);
}
Output:
2015-06-29 15:20:51.874 NexGV1[1684:60b] Notice:
Undefined variable: tennis_court in
/Applications/XAMPP/xamppfiles/htdocs/FilterQuery.php on line
21
{"swimming_pool":"0","security":"0","lift":"0","gym":"0","reserved_parking":"0","visitor_parking":"0","power_backup":"0","servant_room":"0","tennis_court":"0","rainwater_harvesting":"0","waste_management":"0","club_house":"0","desc":"Dkkd","city":"City","pincode":"Pin
Co","locality":"locality","no_of_beds":"1","no_of_baths":"4"}
2015-06-29 15:20:51.875 NexGV1[1684:60b]
(null),(null),(null),(null),(null),(null),(null)
It is showing null value. Why?
This is suppose to be a comment but it's too long for a comment..
So, your approach is json request via url, it is not the ideal for something like this it is confusing and hard to read..
I'm so lazy checking that very long url, so i'll just introduce you to this kind of approach..
NSString *selectQuery=[NSString stringWithFormat:#"http://localhost/FilterQuery.php?swimming_pool=%li&&security=%li&&lift=%li&&gym=%li&&visitor_parking=%li&&power_backup=%li&&servant_room=%li&&rainwater_harvesting=%li&&waste_management=%li&&clubhouse=%li&&Posdesc=%#&&no_of_baths=%li&&no_of_beds=%li&&pincode=%li&&locality=%#&&protypedesc=%#",(long)swimpoolb,(long)securityb,(long)liftb,(long)gymb,(long)visparkingb,(long)pbu,(long)servantroom,(long)rainwaterh,(long)wastemanagement,(long)clubHouse,possesion,(long)bathrooms,(long)bedrooms,(long)zipcode,locality,propertyType];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:selectQuery]];
You can convert that url to request then use the NSURLConnection below..
__block NSMutableData *fragmentData = [NSMutableData data];
__block id serializedResponse;
[[NSOperationQueue mainQueue] cancelAllOperations];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
[fragmentData appendData:data];
if ([data length] == 0 && error == nil)
{
NSLog(#"No response from server");
}
else if (error != nil && error.code == NSURLErrorTimedOut)
{
NSLog(#"Request time out");
}
else if (error != nil)
{
NSLog(#"Unexpected error occur: %#", error.localizedDescription);
}
else if ([data length] > 0 && error == nil)
{
if ([fragmentData length] == [response expectedContentLength])
{
NSLog(#"Received %f of data from server.", (CGFloat)[response expectedContentLength]);
serializedResponse = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
NSLog(#"%#", serializedResponse);
// or
NSLog(#"%#", [[NSString alloc] initWithData:fragmentData encoding:NSUTF8StringEncoding]);
}
}
}];
And also if you like the easy way to make a request using the NSURLConnection above.
- (NSURLRequest *)convertToRequest:(NSString *)stringURL withDictionary:(NSDictionary *)dictionary
{
NSError *error = nil;
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
NSURL *url = [NSURL URLWithString:stringURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: JSONData];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept-Encoding"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[JSONData length]] forHTTPHeaderField:#"Content-Length"];
return request;
}
and using it like:
NSDictionary *jsonDictionary = #{
#"swimming_pool": [NSNumber numberWithLong:(long)swimpoolb],
#"security" : [NSNumber numberWithLong:(long)securityb],
.. and so on
};
NSURLRequest *request = [ImplementationClass convertToRequest:YourServerURL withDictionary: jsonDictionary];
and in the server it should be:
$handle = fopen('php://input','r');
$jsonInput = fgets($handle);
$json_decoded = json_decode($jsonInput,true);
$json_decoded['swimming_pool'];
$json_decoded['security'];
Hope this is informative and helpful...