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];
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);
}
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);
}];
I'm currently working with YouTube API and allowing users to subscribe to other channels, however now I'm supposed to send a POST method that includes a "Request Body".
Here's the Request that's I'm supposed to send :
POST https://www.googleapis.com/youtube/v3/subscriptions?part=snippet&key={YOUR_API_KEY}
//The Request Body
{
"snippet": {
"resourceId": {
"channelId": "UCJZ7f6NQzGKZnFXzFW9y9UQ"
}
}
}
Here's my current code
+(void)subscribeToChannel:(NSString *)channelID {
GTMOAuth2Authentication *auth;
auth = [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName clientID:clientIDclientSecret:clientSecret];
NSString *urlStr;
NSMutableURLRequest *request;
urlStr = [NSString stringWithFormat:#"https://www.googleapis.com/youtube/v3/subscriptions?id=%#&key=mykey", channelID];
[request setHTTPBody:[#"{ \"snippet\": { \"resourceId\": { \"channelId\": \"UCJZ7f6NQzGKZnFXzFW9y9UQ\" } } }" dataUsingEncoding:NSUTF8StringEncoding]];
NSURL *url = [NSURL URLWithString:urlStr];
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[auth authorizeRequest:request
completionHandler:^(NSError *error) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
(unsigned long)NULL), ^(void) {
NSString *output = nil;
if (error) {
output = [error description];
NSLog(#"ERRO LOADING INFO : %#", output);
} else {
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:nil];
if (data) {
output = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
} else {
output = [error description];
}
}
});
}];
}
I'm positive that I'm doing something wrong in [request setHTTPBody] but that's the only thing that I could think about.
You're attempting to set the NSMutableURLRequest's HTTPBody before you have allocated an instance of NSMutableURLRequest.
NSString *urlStr;
// The request is nil
NSMutableURLRequest *request;
urlStr = [NSString stringWithFormat:#"https://www.googleapis.com/youtube/v3/subscriptions?id=%#&key=mykey", channelID];
// At this point the request is still nil so you are attempting to set the HTTPBody on a nil object
[request setHTTPBody:[#"{ \"snippet\": { \"resourceId\": { \"channelId\": \"UCJZ7f6NQzGKZnFXzFW9y9UQ\" } } }" dataUsingEncoding:NSUTF8StringEncoding]]
You also mentioned in a comment that you are receiving a "This API does not support parsing form-encoded input." error. You may be receiving this error because you are not setting the content-type (I came to this conclusion from googling the error. I may be wrong).
This should work:
NSString * urlStr = [NSString stringWithFormat:#"https://www.googleapis.com/youtube/v3/subscriptions?id=%#&key=mykey", channelID];
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
// Set the content type
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// Create the dictionary that you will be using in the HTTPBody
NSDictionary * httpBody = #{
#"snippet": #{
#"resourceId": #{
#"channelId": channelID
}
}
};
// Make sure that the above dictionary can be converted to JSON data
if([NSJSONSerialization isValidJSONObject:httpBody])
{
// Convert the JSON object to NSData
NSData * httpBodyData = [NSJSONSerialization dataWithJSONObject:httpBody options:0 error:nil];
// set the http body
[request setHTTPBody:httpBodyData];
}
I do this when bumping places using the Google Places API, but it should work the same.
Try this:-
NSMutableDictionary *channelId = [[NSMutableDictionary alloc]init];
[channelId setObject:#"UCJZ7f6NQzGKZnFXzFW9y9UQ" forKey:#"channelId"];
NSMutableDictionary *resourceId = [[NSMutableDictionary alloc]init];
[resourceId setObject:channelId forKey:#"resourceId"];
NSDictionary * postDictionary = [NSDictionary dictionaryWithObject:resourceId forKey:#"snippet"];
NSError * error = nil;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:postDictionary options:NSJSONWritingPrettyPrinted error:&error];
[request setHTTPBody:jsonData];
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;
}
}
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"]);
}