Getting JSON Response issue - ios

Currently i am using .net Api's for getting response
Here is my iOS source code:
-(void)getUserNameFromFacebbok: (NSString*)newUserName withFacebookId: (NSString*)newFbId withFacebookLoginEmailId: (NSString*)newEmailId withProfilePicUrl: (NSString*)newProfilePicUrl{
NSString * fbApiURLStr =[NSString stringWithFormat:#"http://example.com/api/v1/FacebookUserLogin?UserName=%#&id=%#&emailid=%#&facebookurl=%#",
newUserName,
newFbId,
newEmailId,
newProfilePicUrl];
NSMutableURLRequest *dataRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:fbApiURLStr]];
NSHTTPURLResponse *response =[[NSHTTPURLResponse alloc] init];
NSError* error;
NSData *responseData = [NSURLConnection sendSynchronousRequest:dataRequest returningResponse:&response error:&error];
facebookLoginResponseDict = [NSJSONSerialization JSONObjectWithData:responseData
options:0
error:&error];
}
I am not getting any response dataRequest parameter ====> currently i am getting { URL: (null) }
Can you please help me out how can i solve this issue

Sorry, I found the proper solution like
NSURL *url = [NSURL URLWithString:#"http://example.com/api/v1/FacebookUserLogin?UserName=Brahmam&id=4654566&emailid=ghjnghjnhgh#gmail.com&facebookurl=https://fbjghjghjghjghmkjhgmhjkmhjmh"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response;
NSError *error;
//send it synchronous
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// check for an error. If there is a network error, you should handle it here.
if(!error)
{
//log response
NSLog(#"Response from server = %#", responseString);
}

Related

NSJSONSerialization get error "index 1 beyond bounds for empty array"

sometimes I get error "index 1 beyond bounds for empty array" at this line
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
This is my full code
+ (NSDictionary *)getJson: (NSString *)strURL parameters:(NSDictionary *)parameters{
NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:15.0];
NSDictionary *headers = #{ #"content-type": #"application/json",
#"cache-control": #"no-cache",
#"postman-token": #"374a4b6f-b660-78f2-78bf-e22cf0156d8d"};
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];*
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:aData options: NSJSONReadingMutableContainers error:&error];
return json;
}
Sometimes I get error, Sometimes not. I don't understands ? please help me, thanks everyone.
Whenever you get an error like the above, try the following:
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:aData options: NSJSONReadingMutableContainers error:&error];
if (error)
{
//1. See what the error says
NSLog(error.localizedDescription);
//2. Convert the original data into a string
NSString *jsonString = [[NSString alloc] initWithData:aData encoding: NSUTF8StringEncoding];
//Now take this string and validate it as a JSON at a place like http://jsonlint.com/
}
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: url
cachePolicy: defaultCachePolicy
timeoutInterval: defaultTimeoutInSeconds];
plz change your cachePolicy with defaultCachePolicy and try :)

responseString from json parse nil

I want to parse a json from an url given by soundcloud.
NSURL *url = [NSURL URLWithString:test[indexPath.row]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSData* jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSDictionary* allKeys = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONWritingPrettyPrinted error:&jsonError];
Url has this form:
https://api.soundcloud.com/tracks/195677713/stream?client_id=3e6cb435319c6fdaad56ff5641e0f89e
but responseString is nil .
Any ideea why ?

NSInvalidArgumentException', reason: 'data parameter is nil

Some time when I call this piece of code *data is nil. It works most of the times except for certain situations which I'm not able to find.
Does anyone know why data could be nil and under which circumstances it could happen?
Some times *data isn't nil but it isn't what I'm expecting (for example I'm getting "login_okit_IT" instead of "login_ok")
Here is the code:
+ (NSDictionary *)eseguiRichiestaConURL:(NSString *)urlScript
{
NSString *rawStr = [NSString stringWithFormat:#""];
NSData *data = [rawStr dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSURL *url = [NSURL URLWithString:urlScript];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:data];
//[request setTimeoutInterval:10000];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"%#", responseData);
NSString *responseString = [NSString stringWithUTF8String:[responseData bytes]];
//NSLog(#"%#", responseString);
NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
if(responseData == nil)
NSLog(#"------ PARAMETRI VUOI -------");
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&e];
return dict;
}
Thanks in advance.

Proper JSON encoding for HTTP POST request in iOS

Posted a query previously about JSON parsing not working properly. Did more looking into it with a packet sniffer and also with another client that works properly and found out it's a syntax thing, that I still can't seem to solve.
The code in the bottom makes the HTTP request to have the JSON in it as:
{"key":"value"}
And my server is actually looking for a JSON in the following syntax:
key=%22value%22
I tried to write some code that does this manually, but figured there must be something out of the box for iOS, and I don't want to have faults in the future.
I messed around with it for a while trying to find the right code for the job, but couldn't (you can see some code I tried commented out). Can anyone help me?
+ (NSString*)makePostCall:(NSString*)urlSuffix
keys:(NSArray*)keys
objects:(NSArray*)objects{
NSDictionary *params = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
// NSString *dataString = [self getDataStringFromDictionary:params];
// NSData *jsonData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
options:0
error:&error];
// id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
// NSLog(#"%#", jsonObject);
if (!jsonData) {
// should not happen
NSError *error;
NSLog(#"Got an error parsing the parameters: %#", error);
return nil;
} else {
// NSString *jsonRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// NSLog(#"%#", jsonRequest);
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#", urlPrefix, urlSuffix]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
// NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
// [request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: jsonData];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
// TODO: handle error somehow
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return returnString;
}
}

iOS: AFJSONRequestOperation Encoding result in NSInvalidArgumentException - 'data parameter is nil'

I'm trying to get a JSon string but some words has "á, é, ç", etc.
The JSon is:
{"Error":"", "Result":{"Transacoes": [{"ClienteID":"1","ID":"915","Banco":"Bradesco","Fornecedor":"","Tipo":"Cartão de crédito - Bradesco Visa","ValorCredito":"0,0000","ValorDebito":"4000,0000","Vencimento":"","Pagamento":"03/08/2012 00:00:00","Descricao":"Cartão Bradesco Visa","Lançamento":"03/08/2012 15:18:12"},{"ClienteID":"1","ID":"916","Banco":"Bradesco","Fornecedor":"","Tipo":"Alinhamento da Conta Bancária","ValorCredito":"22398,9200","ValorDebito":"0,0000","Vencimento":"","Pagamento":"02/08/2012 00:00:00","Descricao":"FGTS","Lançamento":"07/08/2012 11:12:16"}]}}
And the code is:
-(void)viewWillAppear:(BOOL)animated {
NSString *urlAddress = [NSString stringWithFormat:#"http://SITE?action=transacoes&AuthToken=%#&DataDe=02/08/2012&DataAte=03/08/2012", self.usuario.authToken];
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest: request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"%#", JSON);
}
failure: ^(NSURLRequest *request , NSURLResponse *response , NSError *error , id JSON){
NSLog(#"ERROR: %#", error);
}];
[operation start];
}
Your app throws Exception because it can't get data from server ,which you are requesting. SO first make sure it receives some data and then implement following code
Try Following code to parse your json data, i tried with my app, its working fine with that special symbols as well.
NSString *urlAddress = [NSString stringWithFormat:#"http://SITE?action=transacoes&AuthToken=%#&DataDe=02/08/2012&DataAte=03/08/2012", self.usuario.authToken];
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSHTTPURLResponse* urlResponse = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
if([responseData bytes] > 0)
{
// It will work only IOS 5.0 or later version otherwise you can use any third party JSON parsers (eg. SBJSON)
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:NSJSONReadingMutableLeaves
error:&error];
NSLog(#"%#",[[[[json objectForKey:#"Result"] objectForKey:#"Transacoes"] objectAtIndex:1] valueForKey:#"Descricao"]);
NSLog(#"%#",[[[[json objectForKey:#"Result"] objectForKey:#"Transacoes"] objectAtIndex:1] valueForKey:#"Tipo"]);
}

Resources