Hey i have a mac application with the following code:
NSURL *url;
url = [NSURL URLWithString:#"http://yfrog.com/api/xauth_upload"];
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setDelegate:self];
[request setUseCookiePersistence:NO];
[request setUploadProgressDelegate:self];
[request showAccurateProgress];
[request signRequestWithClientIdentifier:#"w" secret:#"x" tokenIdentifier:#"y" secret:#"z" usingMethod:ASIOAuthHMAC_SHA1SignatureMethod];
[request setPostValue:#"a" forKey:#"key"];
NSData *imageData = [[NSData alloc]initWithContentsOfFile:[draggedFilenames objectAtIndex:0]];
[request setPostValue:imageData forKey:#"media"];
[request startAsynchronous];
But the problem is i always get this response from yfrog servers:
So something is wrong with the image upload. On iPhone it works like this:
[request setData:UIImageJPEGRepresentation(picture, 0.8) withFileName:#"filename.jpg" andContentType:#"image/jpeg" forKey:#"media"];
But this doesn't work cocoa(mac) because there is no method like UIIMageJPEGRepresentation.
Also the authentication works, this cant be the problem. If you ask you about this method signRequestWithClientIdentifier it is from the asihttprequest+oauth wrapper from here:
https://github.com/keybuk/asi-http-request-oauth
So how can i upload the image correctly ?
Thanks so much.
NSData* NSImageJPEGRepresentation(NSImage* image, CGFloat compressionQuality)
{
if(nil == image)return nil;
NSDictionary *dict;
dict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:compressionQuality],
NSImageCompressionFactor,
nil];
NSBitmapImageRep* imageRep;
imageRep = [NSBitmapImageRep imageRepWithData:[image TIFFRepresentation]];
return [imageRep representationUsingType:NSJPEGFileType
properties:dict];
}
Related
I am using "RestKit 0.20.3` in my project,
due to some crucial reasons I am going to convert all my API calls to Ret kit,
please can any one tell me how can I make a same call like below with rest kit
I am sending my ASIHHTP code
please can any one migrate it to Rest kit, I unable to find the way
NSDictionary *dictionary=....;
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#auth/login",KBASEURL]];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request setValidatesSecureCertificate:NO];
[request addRequestHeader:#"Content-Type" value:#"application/json; charset=utf-8"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dataDictionary options:kNilOptions error:nil];
[request setPostBody:(NSMutableData *)jsonData];
[request setContentLength:[jsonData length]];
RKObjectManager *manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:#"https://172.22.221.117/api/v1.0/"]];
NSDictionary *dictionary=[NSDictionary dictionaryWithObjectsAndKeys:#"abc.com",#"email",#"password",#"password", nil];
[manager postObject:nil
path:#"auth/login"
parameters:dictionary
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
}
failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
if(operation.HTTPRequestOperation.response.statusCode==200){
//do your processing
}
}];
I am trying to use an API From Mashape.
When I test the endpoint (JSON response), things are working well,
but the objective-c app-ready code example they give is not working, I get the following errors:
This is my code:
- (IBAction)loadJson:(id)sender
{
NSDictionary* headers = [NSDictionary dictionaryWithObjectsAndKeys:#"xxxxxxxxx", #"X-Mashape-Authorization", nil];
NSDictionary* parameters = [NSDictionary dictionaryWithObjectsAndKeys:[NSURL URLWithString:#"<file url>"], #"files", #"", #"urls", nil];
HttpJsonResponse* response = [[Unirest post:^(BodyRequest* request) {
[request setUrl:#"https://lambda-face-recognition.p.mashape.com/detect"];
[request setHeaders:headers];
[request setParameters:parameters];
}] asJson];
}
Is there any way to solve this?
Thanks!
The code examples show this is actually what the code should look like:
NSDictionary* headers = [NSDictionary dictionaryWithObjectsAndKeys:#"application/json", #"accept", nil];
NSDictionary* parameters = [NSDictionary dictionaryWithObjectsAndKeys:#"value", #"parameter", #"bar", #"foo", nil];
HttpJsonResponse* response = [[Unirest postEntity:^(BodyRequest* request) {
[request setUrl:#"http://httpbin.org/post"];
[request setHeaders:headers];
// Converting NSDictionary to JSON:
[request setBody:[NSJSONSerialization dataWithJSONObject:headers options:0 error:nil]];
}] asJson];
Or, maybe this one:
NSDictionary* headers = [NSDictionary dictionaryWithObjectsAndKeys:#"application/json", #"accept", nil];
NSURL file = nil;
NSDictionary* parameters = [NSDictionary dictionaryWithObjectsAndKeys:#"value", #"parameter", file, #"file", nil];
HttpJsonResponse* response = [[Unirest post:^(MultipartRequest* request) {
[request setUrl:#"http://httpbin.org/post"];
[request setHeaders:headers];
[request setParameters:parameters];
}] asJson];
How it do so that I will not need to put data object right in selector call method?
code with warning (Local declaration of data) :
NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:#"SiluetaImage", #"ACTION", silueta_id, #"siluetaid", siluetaTyp_id, #"siluetatypid", nil];
[self performSelector:#selector(downloadBinDataForTyp:data:)
withObject:#"SiluetaImage"
withObject:data];
code without warning :
[self performSelector:#selector(downloadBinDataForTyp:data:)
withObject:#"SiluetaImage"
withObject:[NSDictionary dictionaryWithObjectsAndKeys:#"SiluetaImage", #"ACTION", silueta_id, #"siluetaid", siluetaTyp_id, #"siluetatypid", nil]];
the selector:
- (void)downloadBinDataForTyp:(NSString *)typ data:(NSDictionary*)data
{
ASINetworkQueue *q = [self queue];
NSString *sUrl = #"url_web_service";
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:sUrl]];
NSString *msgLength = [NSString stringWithFormat:#"%d", [[self getMsg] length]];
[request setTimeOutSeconds:60];
[request addRequestHeader: #"Content-Type" value:#"text/xml; charset=utf-8"];
[request addRequestHeader: #"SOAPAction" value:_action];
[request addRequestHeader: #"Content-Length" value:msgLength];
[request setRequestMethod: #"POST"];
request.userInfo = data;
[request appendPostData:[self getMsg]];
[request setDelegate:self];
[q addOperation:request];
[q go];
}
NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:#"SiluetaImage", #"ACTION", silueta_id, #"siluetaid", siluetaTyp_id, #"siluetatypid", nil];
[self performSelector:#selector(downloadBinDataForTyp:data:)
withObject:#"SiluetaImage"
withObject:data];
In this you are passing data whose scope is just to the method. And outside the method it can not be accessed, as it is getting released.
I am trying to send a post value to my server.
It successfully send English characters.
This code is for finding friend, and it can't send UTF-8 text.
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope{
/*
Update the filtered array based on the search text and scope.
*/
if(![searchText isEqualToString:#""]){
NSUserDefaults * userdef = [NSUserDefaults standardUserDefaults];
NSString *encodedSearchText = [searchText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString * uploadUrl = [NSString stringWithFormat:#"%#/%#" , GPON_URL , GPON_URL_SEARCHFRIEND];
NSURL *url = [NSURL URLWithString:uploadUrl];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:encodedSearchText forKey:#"u_id"];
[request setPostValue:[userdef objectForKey:KEY_USER_ID] forKey:#"s_username"];
[request startSynchronous];
[request setShouldAttemptPersistentConnection:NO];
NSString *response = [request responseString];
SBJsonParser * parser = [[[SBJsonParser alloc] init] autorelease];
NSDictionary * json = (NSDictionary *)[parser objectWithString:response];
[searchMember removeAllObjects];
if( [[json objectForKey:#"result"] isEqual:#"YES"] ){
[searchMember addObjectsFromArray:[json objectForKey:#"data"]];
[self.tableView reloadData];
}
}
}
here is my code. can you see what cause the error?
You don't appear to be setting the string encoding of the request; try:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setStringEncoding:NSUnicodeStringEncoding];
Also, this is a very poor way of determining if an NSString is empty:
if (![searchText isEqualToString:#""])
Use the length method instead:
if ([searchText length] > 0)
i had a problem with a NSMutableURLRequest, i want to translate this
curl -b $cookie -F "data=foo" -F "user=bar" http://some/stuff.cgi -H 'X-Requested-With: XMLHttpRequest
my code is
NSString *params = [NSString stringWithFormat:#"data=%#&user=bar", aUrl];
NSURL *url = [NSURL URLWithString:[[NSString alloc] initWithFormat:[NSString stringWithFormat:#"http://%#:%d/stuff.cgi", _host, _port]]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:5.0];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding ]];
[request setValue:[NSString stringWithFormat:#"http://%#/stuff.php", _host] forHTTPHeaderField:#"Referer"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"XMLHttpRequest" forHTTPHeaderField:#"X-Requested-With"];
NSArray *availableCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://%#", _host]]];
NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:availableCookies];
[request setAllHTTPHeaderFields:headers];
NSLog(#"headers: %#", [request allHTTPHeaderFields]);
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
...
but it don't work, i'm make search without results and i' don't know where is the problem.
Thanks.
Solved, just specifie length
[request setValue:[[NSString alloc] initWithFormat:#"%d", [params length]] forHTTPHeaderField:#"Content-Length"];