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

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

Related

NSURLSession Request returns 404 but works fine on Postman

NSString *URLString = #"http://api.sandbox.africastalking.com/version1/airtime/send";
NSString *encodedString = [URLString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:encodedString];
NSDictionary *body = #{
...
};
// convert the dictionary into json data
NSError *error;
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
// Create a post request with the json as a request body.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = #"POST";
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
request.HTTPBody = JSONData;
// create the task.
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!error) {
NSLog(#"Status code: %li", (long)((NSHTTPURLResponse *)response).statusCode);
NSLog(#"Response: %#", response);
NSString *responseText = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response Text: %#", responseText);
} else {
NSLog(#"Error: %#", error.localizedDescription);
}
}];
[task resume];
The code returns "The requested resource could not be found" 404 as response but when I try this request in my REST client (Postman) it works fine.
Try a url with the URLWithString method
NSURL *url = [NSURL URLWithString:#"http://api.sandbox.africastalking.com/version1/airtime/send"];

Getting JSON Response issue

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

Malformed access token facebook ios

I need to get place_id from facebook for facebook checkin section.For that i am using following code.While requesting place id with access token sometines i get message as malformed access token,sometimes expired.
NSString *fbToken = [FBSession activeSession].accessTokenData.accessToken;
NSString *fbURL = [NSString stringWithFormat:#"https://graph.facebook.com/search?q=ritual&type=place&center=9.952786,76.339828&distance=1000&access_token=%#",fbToken];
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",fbURL, fbToken]];
NSLog(#"URL:%#",URL);
NSURLRequest *placeRequest = [NSURLRequest requestWithURL:URL];
//Send the request
[NSURLConnection sendAsynchronousRequest:placeRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if (!connectionError) {
NSDictionary *Data = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(#"data = %#"Data);
}
}];

NSData is null issues

NSString *urlString = [NSString stringWithFormat:#"%#", item.image];
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData * data = [NSData dataWithContentsOfURL:url];
NSDictionary *regsiter=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"response : %#",[regsiter valueForKeyPath:#"response"]);
This NSData values is getting null.
And i need to upload image also same this link how its possible please help me....
If data is null, then it means it could not be created. But if you want to know the reason, you should use dataWithContentsOfURL:options:error: method.
Example:
NSError* error = nil;
NSData * data = [NSData dataWithContentsOfURL:url options:nil error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
}
You can fetch data from URL asynchronously
NSString *url = [NSString stringWithFormat:item.image];
NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[NSURLConnection sendAsynchronousRequest:req
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *responce,
NSData *data,
NSError *error) {
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"String from URL %# is %#", url, str);
}];

HTTP POST request to send an image

I'm trying to post an image to a webservice by means of an HTTP POST request.
The API doc says that image parameter should be the "binary file data for the image you would like analyzed - PNG, GIF, JPG only."
This is the code I'm trying to use:
UIImage *image = [UIImage imageNamed:#"air.jpg"];
NSData *imgData = UIImageJPEGRepresentation(image, 1.0);
NSURLResponse *response;
NSError *error = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://pictaculous.com/api/1.0/"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:imgData];
NSData *receivedData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if(error!=nil) {
NSLog(#"web service error:%#",error);
}
else {
if(receivedData !=nil) {
NSError *Jerror = nil;
NSDictionary* json =[NSJSONSerialization
JSONObjectWithData:receivedData
options:kNilOptions
error:&Jerror];
if(Jerror!=nil) {
NSLog(#"json error:%#",Jerror);
}
}
}
The problem is that in the JSON response I always receive the error "You must provide an image" as if the format of the received image was not correct.
Isn't "UIImageJPEGRepresentation" the correct way to get binary data from an image ?
Is there any other way I can get the binary file data from my JPEG image ?
Thanks,
Corrado
If you want to simplify your code, you can use a simple NSURLConnection wrapper such as STHTTPRequest.
STHTTPRequest *r = [STHTTPRequest requestWithURLString:#"http://pictaculous.com/api/1.0/"];
NSString *path = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"jpg"];
NSData *data = [NSData dataWithContentsOfFile:path];
[r addDataToUpload:data parameterName:#"image"];
r.completionBlock = ^(NSDictionary *headers, NSString *body) {
NSLog(#"-- %#", body);
};
r.errorBlock = ^(NSError *error) {
NSLog(#"-- error: %#", error);
};
[r startAsynchronous];

Resources