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);
}];
Related
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);
}
I need to do this GET request:
http://api.testmy.co.il/api/sync?BID=1049&ClientCode=3847&Discount=2.34&Service=0&Items=[{"Name":"Tax","Price":"2.11","Quantity":"1","SerialID":"1","Remarks":"","Toppings":""}]&Payments=[]
In browser I get this response:
{
"Success": true,
"Atava": [],
"Pending": [],
"CallWaiter": false
}
But in iOS its not working.
I try:
NSString *requestedURL=[NSString stringWithFormat:#"http://api.testmy.co.il/api/sync?BID=%i&ClientCode=%i&Discount=2.34&Service=0&Items=[{\"Name\":\"Tax\",\"Price\":\"2.11\",\"Quantity\":\"1\",\"SerialID\":\"1\",\"Remarks\":\"\",\"Toppings\":\"\"}]&Payments=[]",BID,num];
NSURL *url = [NSURL URLWithString:requestedURL];
NSURLResponse *response;
NSData *GETReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString *theReply = [[NSString alloc] initWithBytes:[GETReply bytes] length:[GETReply length] encoding: NSASCIIStringEncoding];
NSLog(#"Reply: %#", theReply);
OR
NSString *requestedURL = [NSString stringWithFormat:#"http://api.testmy.co.il/api/sync?BID=%i&ClientCode=%i&Discount=2.34&Service=0&Items=[{'Name':'Tax','Price':'2.11','Quantity':'1','SerialID':'1','Remarks':'','Toppings':''}]&Payments=[]", BID, num];
OR
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
[params setObject:#"Tax" forKey:#"Name"];
[params setObject:#"2.11" forKey:#"Price"];
[params setObject:#"1" forKey:#"Quantity"];
[params setObject:#"1" forKey:#"SerialID"];
[params setObject:#"" forKey:#"Remarks"];
[params setObject:#"" forKey:#"Toppings"];
NSData *jsonData = nil;
NSString *jsonString = nil;
if([NSJSONSerialization isValidJSONObject:params])
{
jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:nil];
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#", jsonString);
}
NSString *get = [NSString stringWithFormat:#"&Items=%#", jsonString];
NSData *getData = [get dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"GET"];
[request setTimeoutInterval:8];
[request setHTTPBody:getData];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
I tried all above code but it doesn't work(long time out.. just stuck on this).How to fixing this?
This is because your URL is not correct, this string should add percent escape. Try with this:
NSString *requestedURL=[NSString stringWithFormat:#"http://api.testmy.co.il/api/sync?BID=%i&ClientCode=%i&Discount=2.34&Service=0&Items=[{'Name':'Tax','Price':'2.11','Quantity':'1','SerialID':'1','Remarks':'','Toppings':''}]&Payments=[]",BID,num];
NSURL *url = [NSURL URLWithString:[requestedURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//and you use this url
// Send a synchronous request
NSURLRequest * urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:#"enter your url here"]];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
if (error == nil)
{
// Parse data here
}
The NSURLResponse and NSError vars are passed into the sendSynchronousReqeust method so when it returns, they will be populated with the raw response and error (if any). If you need to check for stuff like response codes you can do so via the “response” variable you pass.
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];
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.
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"]);
}