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...
Related
A POST API throws error when I call it in my code while gives a success response through postman. I use the same method to call other services and they work just fine. The problem is with this particular API. Here is the code I use for calling the API:
-(void)createNSUrlSessionLogin:(NSURL*)URL postDict:(NSDictionary*)dict successBlock:(completionBlock)completionBlock
failureBlock:(failureBlock)failure
{
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
NSData *postData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if ([data length] > 0 && error == nil)
{
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"result json: %#", jsonArray);
if (!jsonArray) {
failure(NO,nil);
}else
{
completionBlock(YES,jsonArray);
}
}
else if ([data length] == 0 && error == nil){
failure(NO,nil);
}
else if (error != nil){
NSLog(#"Error is %#",[error description]);
failure(NO,nil);
}
}];
[postDataTask resume];
}
Any help is appreciated.
I'm sorry, i'm cannot write comments. But I see, that you do content-type: url-encoded request via postman, and application-json via code. If API accept only url-encoded requests, this is your answer.
Try this...
-(void)serverRequestFetchData:(NSMutableURLRequest*)request withCallback:(void (^)(NSArray *, NSError *))aCallback {
NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
dispatch_sync(dispatch_get_main_queue(), ^{
NSHTTPURLResponse *statusResponse = (NSHTTPURLResponse *)response;
if (statusResponse.statusCode >= 200 && statusResponse.statusCode < 300) {
if (data.length > 0 && error == nil) {
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
if (aCallback) {
aCallback(array, nil);
}
} else {
aCallback(#[], error);
}
} else {
NSString *statusMessage = [NSString stringWithFormat:#"Invalid status response code: %ld", (unsigned long)statusResponse.statusCode];
NSError *statusError = [[NSError alloc] initWithDomain:#"com.somedomain" code:10001 userInfo:#{NSLocalizedDescriptionKey : NSLocalizedString(statusMessage, nil)}];
if (aCallback) {
aCallback(#[], statusError);
}
}
});
}];
[dataTask resume];
}
-(void)myRequest {
NSString *jsonRequest = [NSString stringWithFormat:#"{\"access_token\":\"ACCESS_TOKEN_HERE\"}"];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
NSString *URLString = [NSString stringWithFormat:#"YOUR_FIRST_URL_STRING"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URLString]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", (int)[requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
[self serverRequestFetchData:request withCallback:^(NSArray *array, NSError *error) {
}];
}
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 app i have used ASIFormDataRequest earlier days for integrating the services
now i have changed format and i am using NSURLSession instead of ASIFormDataRequest
But when i request change password to server using ASIFormDataRequest success response is coming from server but when i use NSURLSession failed response coming from server please help what is wrong
NSURlsession:-
def = [NSUserDefaults standardUserDefaults];
NSString *myString = [def stringForKey:#"AccesToken"];
NSString *AccessToken = [NSString stringWithFormat:#"Bearer %#",myString];
NSString *Finalstr = [NSString stringWithFormat: #"MedicaidId=%#&OldPassword=%#&NewPassword=%#&ConfirmPassword%#", medicaId,self.CurPwdTxt.text,self.NewPwdTxt.text,self.ConfPwdTxt.text];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:mainurl,BaseURL]]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[Finalstr dataUsingEncoding:NSUTF8StringEncoding]];
[request addValue:AccessToken forHTTPHeaderField:#"Authorization"];
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) {
NSError *parseError;
id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"responseobject is %#",responseObject);
}else{
NSError *parseError;
id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"else condtion");
if (!responseObject) {
NSLog(#"JSON parse error: %#", parseError);
NSLog(#"responseobject is%#",responseObject);
} else {
NSLog(#"responseobject is %#",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];
}
ASIFormDataRequest:-
NSString *urlStr = [NSString stringWithFormat:#"myurl",BaseURL];
NSLog(#"urlStr --->>> %#",urlStr);
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlStr]];
[request setRequestMethod:#"POST"];
def = [NSUserDefaults standardUserDefaults];
NSString *myString = [def stringForKey:#"AccesToken"];
NSString *str = [NSString stringWithFormat:#"Bearer %#",myString];
NSLog(#"token is %#",str);
[request setPostValue:medicaId forKey:#"MedicaidId"];
[request setPostValue:self.CurPwdTxt.text forKey:#"OldPassword"];
[request setPostValue:self.NewPwdTxt.text forKey:#"NewPassword"];
[request setPostValue:self.ConfPwdTxt.text forKey:#"ConfirmPassword"];
[request addRequestHeader:#"Authorization" value:str];
[request setDelegate:self];
[request startAsynchronous];
You are sending different requests there. In the 'new' code, you are constructing the POST data like this:
#"MedicaidId=%#&OldPassword=%#&NewPassword=%#&ConfirmPassword%#"
which looks like GET-parameters more than form-encoding (which you use on the 'old' request).
Tracking your request and checking out the actual request using something like Wireshark might help you out to spot the problem yourself next time.
I am new in iOS application development. I have one problem in login page.
Sometimes it will take long time for log in. I am using this code to send or receive a request from a httpserver.
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonData1
options:0 // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (!jsonData) {
NSLog(#"Got an error: %#", error);
} else {
jsonString= [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"converted json string is %#",jsonString);
}
NSData *postData = [[[NSString alloc] initWithFormat:#"method=methodName&email=%#&password=%#", user_name, pass_word] dataUsingEncoding:NSASCIIStringEncoding ];
NSString *postLength = [NSString stringWithFormat:#"%ld",[postData length]];
jsonData=[jsonString dataUsingEncoding:NSASCIIStringEncoding];
NSLog(#"the final passing json data is %#",jsonData);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http:urladdress"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"\"Accept\""];
[request setValue:#"application/json" forHTTPHeaderField:#"\"Content-Type\""];
[request setValue:postLength forHTTPHeaderField:#"\"Content-Length\""];
[request setValue:#"application/x-www-form-urlencoded;" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
NSError *requestError = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&requestError];
//if communication was successful
if ([response statusCode] >= 200 && [response statusCode] < 300) {
NSError *serializeError = nil;
NSString* newStr = [NSString stringWithString :[urlData bytes]];
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:urlData
options:NSJSONReadingAllowFragments
error:&serializeError];
NSLog(#"recdata %#",jsonData);
}
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection)
{
NSLog(#"theConnection is succesful");
self.receivedData = [NSMutableData data];
}
[connection start];
[self readFromDataBase];
if (dataCheck==true) {
[self checkPassword];
}
is there any way to login faster.?
Maybe the connection is slow because your server or your connection quality.
Did you try with async? It won't freeze your app when waiting the respond
Asynchronous NSURLConnection Scheme Tutorial
For your program, replace the sendSync method:
NSData *urlData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&requestError];
by sendAsync method:
NSOperationQueue *mainQueue = [[NSOperationQueue alloc] init];
[mainQueue setMaxConcurrentOperationCount:5];
[NSURLConnection sendAsynchronousRequest:request queue:mainQueue completionHandler:^(NSURLResponse *response, NSData *urlData, NSError *requestError) {
// doing somethings ...
// if communication was successful ...
}];
I have a simple app which makes a POST request. And then data is returned. The problem is that the returned data is not JSON..... So how can I view it? Here is my code:
NSString *requestString = [NSString stringWithFormat:#"https://serveraddress.com"];
NSString *string = [NSString stringWithFormat:#"id=%#&olt_info=%#", #"test", #"renz"];
NSData *postData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestString]];
NSLog(#"\n request str : %#",request);
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"The responce:\n\n%#", responseData);
if (error == nil && response.statusCode == 200) {
NSLog(#"%li", (long)response.statusCode);
NSError *err;
id JSon = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&err];
if (err) {
NSLog(#"%#",err);
}
else {
NSLog(#"Json %#",JSon);
}
}
else {
//Error handling
NSLog(#"%#", response);
}
This is the format of the returned data that I am trying to read:
new_token=509723045780uIRBWRBH24b
So I know the downloaded data gets stored in the NSData called "responseData". But if I print it using NSLog I just get this:
<61636365 73735f74 6f6b656e 3d313538 32353838 33343337 39343431 7c365f4d 6543436e 6b51716f 722d6e70 61746662 484d6458 526b3477>
So how do I read this???
Thank you for your time, Dan.
To get NSString from NSData use
NSString *decodedString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
maybe this string will have a valid JSON format.
NSString *requestString = [NSString stringWithFormat:#"https://serveraddress.com"];
NSString *string = [NSString stringWithFormat:#"id=%#&olt_info=%#", #"test", #"renz"];
NSData *postData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestString]];
NSLog(#"\n request str : %#",request);
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
*id json = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];*
NSLog(#"%#", json);
if (error == nil && response.statusCode == 200) {
NSLog(#"%li", (long)response.statusCode);
NSError *err;
id JSon = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&err];
if (err) {
NSLog(#"%#",err);
}
else {
NSLog(#"Json %#",JSon);
}
}
else {
//Error handling
NSLog(#"%#", response);
}