Error Domain=NSURLErrorDomain - ios

I am sorry for this question. I am new to iOS.
I am working on xcode 7.1. I am calling a POST call on my Local server but I am getting this error. and I am not sure why. I have been trying and searching for couple of days now, but i couldn't find anything relevant. this is my code
NSString *myUrlString = [NSString stringWithFormat:#"%#%#/login",link,Entry ];
//create string for parameters that we need to send in the HTTP POST body
NSLog(#"My Url = %#",myUrlString);
NSMutableDictionary* postRequestDictionary = [[NSMutableDictionary alloc] init];
postRequestDictionary[#"email" ]= EmailIDTF.text;
postRequestDictionary[#"password" ]= PasswordTF.text;
NSLog(#"body = %#",postRequestDictionary);
NSData *json;
NSString *jsonString;
NSError *error;
// Dictionary convertable to JSON ?
if ([NSJSONSerialization isValidJSONObject:postRequestDictionary])
{
// Serialize the dictionary
json = [NSJSONSerialization dataWithJSONObject:postRequestDictionary options:NSJSONWritingPrettyPrinted error:&error];
// If no errors, let's view the JSON
if (json != nil && error == nil)
{
jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
NSLog(#"JSON: %#", jsonString);
}
}
//create a mutable HTTP request
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[myUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:60.0]; //sets the receiver’s timeout interval, in seconds
[urlRequest setTimeoutInterval:30.0f];
//sets the receiver’s HTTP request method
[urlRequest setHTTPMethod:#"POST"];
[urlRequest addValue:#"application/json" forHTTPHeaderField:#"Content-type"];
NSString *params = [NSString stringWithFormat:#"%#",jsonString];
NSLog(#"param = %#",params);
//sets the request body of the receiver to the specified data.
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
//allocate a new operation queue
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//Loads the data for a URL request and executes a handler block on an
//operation queue when the request completes or fails.
[NSURLConnection
sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(NSURLResponse *response,
NSData *data,
NSError *error) {
if ([data length] >0 && error == nil){
//process the JSON response
//use the main queue so that we can interact with the screen
dispatch_async(dispatch_get_main_queue(), ^{
[self parseResponse1:data];
});
}
else if ([data length] == 0 && error == nil){
NSLog(#"Empty Response, not sure why?");
}
else if (error != nil){
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"Not again, what is the error = %#", error);
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Alert!" message:#"Please check that you are connected to internet." delegate:self cancelButtonTitle:#"I got it." otherButtonTitles: nil];
// spinnerview.hidden=YES;
[alert show];
});
}
}];
But all i am getting is this error
Error Domain=NSURLErrorDomain Code=-1012 "(null)" UserInfo={NSErrorFailingURLKey=http://xyz/login, NSErrorFailingURLStringKey=http://xyz/login, NSUnderlyingError=0x165a0f80 {Error Domain=kCFErrorDomainCFNetwork Code=-1012 "(null)" UserInfo={_kCFURLErrorAuthFailedResponseKey={url = http://xyz/login}}}}
and thing is that why is it giving "(null)"??
Please help me guys. Thanks in advance. 🙏

try after adding this key in your info.plist file:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Hope this helps.

pragma mark call web service with this code
NSString *myUrlString = [NSString stringWithFormat:#"%#%#/login",link,Entry ];
NSMutableDictionary* postRequestDictionary = [[NSMutableDictionary alloc] init];
postRequestDictionary[#"email" ]= EmailIDTF.text;
postRequestDictionary[#"password" ]= PasswordTF.text;
NSString *mystring=[self returnMeParameterString:postRequestDictionary];
NSURL *url = [NSURL URLWithString:myUrlString];
NSData *postData = [mystring dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[mystring length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse response, NSData data, NSError *connectionError) {
if(connectionError)
{
//error
}
else
{
//success
}
}];
pragma mark convert Dictionary to string
-(NSString*)returnMeParameterString:(NSDictionary *)params{
NSMutableString *paramstring = [[NSMutableString alloc] init];
NSMutableArray *keyArray = [[NSMutableArray alloc] init];
NSMutableArray *valueArray = [[NSMutableArray alloc] init];
for( NSString *aKey in [params allKeys] )
{
[keyArray addObject:aKey];
}
for( NSString *aValue in [params allValues] )
{
[valueArray addObject:aValue];
}
for (int k=0; k< keyArray.count; k++)
{
NSString *tempString;
if(k==0)
{
tempString = [NSString stringWithFormat:#"%#=%#",[keyArray objectAtIndex:k],[valueArray objectAtIndex:k]];
}
else
{
tempString = [NSString stringWithFormat:#"&%#=%#",[keyArray objectAtIndex:k],[valueArray objectAtIndex:k]];
}
[paramstring appendString:tempString];
}
return paramstring;
}

Related

iOS objective c retrieving data from server NSUrl not able to access to global variable

hi I am new to iOS and I am giving request to server and getting top to the mobile number and through request reply I am able to get the otp but when I print the data out of the seesion which is initialised inside block I am getting null
this is my .h file
#import <UIKit/UIKit.h>.
#interface OtpViewController : UIViewController
#property (nonatomic,strong) NSString *str;
#property (strong,nonatomic) NSString *tmp;
#property(weak,nonatomic) NSString *requestReply ;
#end
this is my url request block in .m file
- (IBAction)submitb:(id)sender
{
if (_mobiletf.text && _mobiletf.text.length >0 )
{
/* not empty - do something */
NSString *post = [NSString stringWithFormat:#"phone=%#",_mobiletf.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Next up, we read the postData's length, so we can pass it along in the request.
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
// Now that we have what we'd like to post, we can create an NSMutableURLRequest, and include our postData
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.sitesandflats.com/send_otp.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSLog(#"the data Details is %#", post);
// And finally, we can send our request, and read the reply by creating a new NSURLSession:
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; // this is json string
// NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; // you need to convert to dictionary object
NSLog(#"requestReply: %#", jsonDict);
self.tmp=[jsonDict valueForKey:#"otp"] ;
self.str=self.tmp;
NSLog(#"tmp storage inside block:%#",self.tmp);
[self performSelector:#selector(updateStatus) withObject:nil afterDelay:1.0];
// NSLog(#"requestReply: %#", jsonDict);
//self.tmp=[jsonDict valueForKey:#"otp"] ;
//self.str=self.tmp;
//NSLog(#"tmp storage inside block:%#",self.tmp);
}] resume];
//self.str=self.tmp;
NSLog(#" storage:%#",self.str);
NSLog(#"tmp storage:%#",self.tmp);
[ self performSegueWithIdentifier:#"b1" sender:self];
}
else
{
/* what ever */
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Please check your input!!."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
-(void)updateStatus{
NSLog(#" storage:%#",self.str);
NSLog(#"tmp storage:%#",self.tmp);
// [ self performSegueWithIdentifier:#"b1" sender:self];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable id)sender
{
VerifyViewController *loadCtr = (VerifyViewController *)segue.destinationViewController;
loadCtr.otpStr =self.tmp;
loadCtr.mobileStr = _mobiletf.text;
}
this is my print log
2017-06-01 12:44:08.813 MenuBar[2750:135123] the data Details is phone=9047038606
2017-06-01 12:44:08.829 MenuBar[2750:135123] 9047038606
2017-06-01 12:44:08.835 MenuBar[2750:135123] storage:(null)
2017-06-01 12:44:08.836 MenuBar[2750:135123] tmp storage:(null)
2017-06-01 12:44:10.122 MenuBar[2750:135162] requestReply: {
otp = 552749;
success = 1;
}
2017-06-01 12:44:10.122 MenuBar[2750:135162] tmp storage inside block:552749
block is the additional thread , so you need to wait for completion block, so change your code like below
if you want to acces the data in outside
- (IBAction)submitb:(id)sender
{
if (_mobiletf.text && _mobiletf.text.length >0 )
{
/* not empty - do something */
NSString *post = [NSString stringWithFormat:#"phone=%#",_mobiletf.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Next up, we read the postData's length, so we can pass it along in the request.
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
// Now that we have what we'd like to post, we can create an NSMutableURLRequest, and include our postData
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.sitesandflats.com/send_otp.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSLog(#"the data Details is %#", post);
// And finally, we can send our request, and read the reply by creating a new NSURLSession:
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; // this is json string
// NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; // you need to convert to dictionary object
NSLog(#"requestReply: %#", jsonDict);
self.tmp=[jsonDict valueForKey:#"otp"] ;
self.str=self.tmp;
NSLog(#"tmp storage inside block:%#",self.tmp);
[self updateStatus];
}] resume];
}
else
{
/* what ever */
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Please check your input!!."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
-(void)updateStatus{
NSLog(#" storage:%#",self.str);
NSLog(#"tmp storage:%#",self.tmp);
dispatch_async(dispatch_get_main_queue(), ^{
[ self performSegueWithIdentifier:#"b1" sender:self];
});
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable id)sender
{
VerifyViewController *loadCtr = (VerifyViewController *)segue.destinationViewController;
loadCtr.otpStr =self.tmp;
loadCtr.mobileStr = _mobiletf.text;
}

iOS - different response from single API in ARC and parsing

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

How to perform a GET request and check the response

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.

JSON data is not coming from local host

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...

Difference between Post & Get method in Json Parsing in ios

I implement the JSON Parsing as follow:
-(void)getallEvent
{
SBJSON *json = [SBJSON new];
json.humanReadable = YES;
responseData = [[NSMutableData data] retain];
NSString *service = #"/GetAllVenue";
NSString *str;
str = #"Calagary";
NSString *requestString = [NSString stringWithFormat:#"{\"CityName\":\"%#\"}",str];
//NSLog(#"request string:%#",requestString);
// NSString *requestString = [NSString stringWithFormat:#"{\"GetAllEventsDetails\":\"%#\"}",service];
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSString *fileLoc = [[NSBundle mainBundle] pathForResource:#"URLName" ofType:#"plist"];
NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc];
NSString *urlLoc = [fileContents objectForKey:#"URL"];
urlLoc = [urlLoc stringByAppendingString:service];
//NSLog(#"URL : %#",urlLoc);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLoc]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: requestData];
// self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
NSError *respError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
if (respError)
{
NSString *msg = [NSString stringWithFormat:#"Connection failed! Error - %# %#",
[respError localizedDescription],
[[respError userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Check your network connection" message:msg delegate:self cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[alertView release];
}
else
{
NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSDictionary *results = [[responseString JSONValue] retain];
//NSLog(#" %#",results);
NSString *extractUsers = [[results objectForKey:#"d"] retain];
NSDictionary *finalResult = [[extractUsers JSONValue] retain];
NSLog(#"Final Results : %#",finalResult);
listOfEvents = [finalResult objectForKey:#"List of Event details of given Venue"];
}
Using this code, it slow down the app. How can I parse the json in background?
*Is this right for Post Method? what is the difference between Post & Get Method?*
Is there any other way to json parsing?
You are using synchronous request which is executed on Main thread so if you need to do it in background use asynchronous loading.
POST METHOD:
The POST method generates a FORM collection, which is sent as a HTTP request body. All the values typed in the form will be stored in the FORM collection.
GET METHOD: The GET method sends information by appending it to the URL (with a question mark) and stored as A Querystring collection. The Querystring collection is passed to the server as name/value pair. The length of the URL should be less than 255 characters.
An HTTP GET is a request from the client to the server, asking for a resource.
An HTTP POST is an upload of data (form information, image data, whatever) from the client to the server.
Check this answer for more details : what-is-the-difference-between-post-and-get
You are making synchronous communication request which slows down the application. You should make the asynchronous request to keep your app responsive.
It is not having any concern with parsing JSON data.
I would recommend using AFNetworking in your context which will simplify the connection management, background queue execution and parsing of the JSON you are getting back form the server.
The code example below will create an HTTP client with a base URL (<hostname>) and get a JSON payload from a given path. The network request runs in the background and runs a given block when completing
httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
// set the type to JSON
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[httpClient setDefaultHeader:#"Accept" value:#"application/json"];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
// Activate newtork indicator
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
// Request the <path> from the server and parse the response to JSON
// this calls a GET method to <hostname>/<path>
[httpClient getPath:<your path> parameters:Nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
// responseObject is a JSON object here
//
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// handle error
}];
Get: With the get method the value is send through the query string appended with the url. So you can see the the name, value, description on the addressbar when the page display in the browser.
Post: This method transfer the information through the complete form. You can not see the detail description on the addresss bar. When the page display.
NSString *myUrlString =[NSString stringWithFormat: #"your url];
NSString *postdata=[NSString stringWithFormat:#"emailId=%#&password=%#,username,password];
NSLog(#"%#",postdata);
//create a NSURL object from the string data
NSURL *myUrl = [NSURL URLWithString:myUrlString];
//create a mutable HTTP request
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:myUrl];
//sets the receiver’s timeout interval, in seconds
[urlRequest setTimeoutInterval:30.0f];
//sets the receiver’s HTTP request method
[urlRequest setHTTPMethod:#"POST"];
//sets the request body of the receiver to the specified data.
[urlRequest setHTTPBody:[postdata dataUsingEncoding:NSUTF8StringEncoding]];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//Loads the data for a URL request and executes a handler block on an
//operation queue when the request completes or fails.
[NSURLConnection
sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(NSURLResponse *response,
NSData *data,
NSError *error) {
if ([data length] >0 && error == nil){
//process the JSON response
//use the main queue so that we can interact with the screen
dispatch_sync(dispatch_get_main_queue(), ^{
[self parseResponse:data];
});
}
else if ([data length] == 0 && error == nil){
NSLog(#"Empty Response, not sure why?");
}
else if (error != nil){
NSLog(#"Not again, what is the error = %#", error);
}
}];
}
- (void) parseResponse:(NSData *) data
{
responseData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"JSON = %#", responseData);
NSLog(#"Response ==> %#", responseData;
Finally u get the response from that specific url .and what ever u wanted to it do ur own way.

Resources