AFNetworking AFMultipartFormData how to set key - iphone

I want to upload (POST) image to server with setkey "FileData" like before (wrote with ASIHTTPRequest and it works)
[self.request setData:imageData withFileName:dateFormatted andContentType:#"image/jpeg" forKey:#"Filedata"];
with AFNetworking I set like below:
NSMutableURLRequest *afRequest = [httpClient multipartFormRequestWithMethod:#"POST" path:#"" parameters:paramsDic constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:imageData name:#"Filedata" fileName:dateFormatted mimeType:#"image/jpeg"];
}];
seems name not actually works...
How should I set the key? #mattt
Thanks

I figure it out, the problem is I add this line
[afRequest setValue:#"application/x-www-form-urlencoded; charset=UTF8" forHTTPHeaderField:#"Content-Type"];
But I still don't know why, I add this line to other http request and it works, but file upload. I checked server, when do file upload with this line, server received many ... hm... come to think how to describe it, mass letters ...like below:
Content-Type: image/jpeg^M ^M
ÿØÿà^#^PJFIF^#^A^A^#^#^A^#^A^#^#ÿá^#XExif^#^#MM^#*^#^#^#^H^#^B^A^R^#^C^#^#^#^A^#^A^#^#<87>i^#^D^#^#^#^A^#^#^#

hi i am uploading audio/image file as below please check it and its working fine using the ASIHTTPRequest.
NSURL *audiourl = [NSURL URLWithString:#"Your Url"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:audiourl];
NSData *postData = [NSData dataWithContentsOfURL:SoundPath];
//SoundPath is your audio url path of NSDocumentDirectory.
[request addData:postData withFileName:#"mynewfile.png" andContentType:#"image/png" forKey:#"FileData"];
[request setDelegate:self];
[request startasynchronous];
Thanks

Related

How to download audio files

I want to download audio files Asynchronously from internet through ASIHTTP request. I have written a piece of code, but it's not working properly.
+(ASIHTTPRequest *)getDownloadedLectureAndSeries:(id)target :(NSString *)downloadString FinishSelector:(SEL) finishselector FailSelector:(SEL) failselector
{
NSString *api=downloadStrin;
NSURL *url = [NSURL URLWithString:api];
[api release];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request startAsynchronous];
[request setDelegate:target];
[request setDidFinishSelector:finishselector];
[request setDidFailSelector:failselector];
return request;
}
Help me, if you can. Thanks in advance.
Doesn't look like you are acctually saving the file anywhere in your code. (Unless you are trying to do it in your finishselector.
Add this line to have the request automatically save the file
[request setDownloadDestinationPath:path];
Where path is a NSString to where you want the file to be stored (such as your Documents directory

ASIHTTPFormDataRequest- "Unable to create request (bad url?)"

I have the following requirement to call a service using an ASIHTTPRequest with a POST method call. When I execute the request I get the following error:
errorError Domain=ASIHTTPRequestErrorDomain Code=5 "Unable to create request (bad url?)" UserInfo=0x790b490 {NSLocalizedDescription=Unable to create request (bad url?)}
And heres my code:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:SampleURL]];
[request addPostValue:#"emailid" forKey:username.text];
[request addPostValue:#"password" forKey:password.text];
[request addPostValue:#"first_name" forKey:first_name];
[request addPostValue:#"last_name" forKey:last_name];
[request addPostValue:#"option" forKey:#"userSignup"];
request.delegate = self;
[request startSynchronous];
Can anyone help me on this?
NSString *safestring=[strUrl stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL *url= [NSURL URLWithString:safestring];
[request addPostValue:#"emailid" forKey:username.text];
Shouldn't that be in the opposite order: [request addPostValue:username.text forKey:#"emailid"];
Same for the rest...
It looks like that 'sampleURL' has some issue. What is the data type of sampleUL? it should be NSURL.
Also what is in sampleURL when this piece of code is executed.

ASIFormDataRequest: "No file exists at path" while it does

I'm trying to upload a file using ASIFormDataRequest
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString: uploadUrl]] autorelease];
[request setPostValue:md5sum forKey:#"md5sum"];
[request setFile:[NSString stringWithFormat:#"%#", filePath] forKey:#"database"];
[request startSynchronous];
This logs an error:
"No file exists at: file://localhost/Users/thomas/Library/Application%20Support/iPhone%20Simulator/5.0/Applications/36115C00-9352-4CD4-B5C2-C3A1CD6041FF/Documents/foo.sqlite"
However when I try the path in my browser. It downloads the file straight away, so the file does exist.
Anyone got a clue?
Thanks!
Try to use POSIX path:
[request setFile:[[NSURL URLWithString:filePath] path] forKey:#"database"];
I suspect it's the %20 that makes troubles. Try unescaping the filePath variable:
filePath = [filePath stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

Do a GET request with parameters on iPhone SDK?

I'm doing an app which retrieves user info, and it does that using a GET request, but I don't know how could I make one. Already tried ASIHTTPRequest with this code:
NSURL *url = [NSURL URLWithString:#"http://forrst.com/api/v2/users/info"];
// Now, set up the post data:
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setPostValue:#"1" forKey:#"id"];
[request setRequestMethod:#"GET"];
// Initiate the WebService request
[request setDelegate:self];
[request startAsynchronous];
But I get this response from forrst:
2011-06-05 16:59:32.189 Forrsty[4335:207] {"resp":{"error":"you must pass either id or username"},"stat":"fail","in":0.0557,"authed":false,"authed_as":false,"env":"prod"}
Which I understand I'm not doing the GET request ok, so how I would do it? Thanks :)
A Get Parameter ?
So why don't you try "http://forrst.com/api/v2/users/info?id=1" ?
[ NSString stringWithFormat:#"http://forrst.com/api/v2/users/info?id=%d", 1 ];
By the way, take a look at this librayry : http://allseeing-i.com/ASIHTTPRequest/
Good luck !

Having problems with uploading photos to TwitPic using OAuth in Objective C on the iPhone

I have been working on an iPhone app that has a feature of uploading photos to TwitPic. I have it working with basic authentication.
I am trying to get it working with OAuth. I am getting authentication errors. I have studied very carefully the TwitPic documentation.
I am authorising the app by displaying a UI Web View and the it returns a PIN value. I enter the PIN value in the app and request the token.
I am able to upload status updates to Twitter but not photos.
My code is based on some example code from here:
Example iPhone app using OAuth
Here is my code:
NSString *url = #"http://api.twitpic.com/2/upload.json";
NSString *oauth_header = [oAuth oAuthHeaderForMethod:#"POST" andUrl:url andParams:nil];
NSLog(#"OAuth header : %#\n\n", oauth_header);
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:url]];
[request addRequestHeader:#"User-Agent" value:#"ASIHTTPRequest"];
request.requestMethod = #"POST";
[request addRequestHeader:#"X-Auth-Service-Provider" value:#"https://api.twitter.com/1/account/verify_credentials.json"];
[request addRequestHeader:#"X-Verify-Credentials-Authorization" value:oauth_header];
NSData *imageRepresentation = UIImageJPEGRepresentation(imageToUpload, 0.8);
[request setData:imageRepresentation forKey:#"media"];
[request setPostValue:#"Some Message" forKey:#"message"];
[request setPostValue:TWITPIC_API_KEY forKey:#"key"];
[request setDelegate:self];
[request setDidFinishSelector:#selector(requestDone:)];
[request setDidFailSelector:#selector(requestFailed:)];
[request start];
Here is the OAuth Header:
OAuth realm="http://api.twitter.com/", oauth_timestamp="1275492425", oauth_nonce="b686f20a18ba6763ac52b689b2ac0c421a9e4013", oauth_signature_method="HMAC-SHA1", oauth_consumer_key="zNbW3Xi3MuS7i9cpz6fw", oauth_version="1.0", oauth_token="147275699-jmrjpwk3B6mO2FX2BCc9Ci9CRBbBKYW1bOni2MYs", oauth_signature="d17HImz6VgygZgbcp845CD2qNnI%3D"
HA! I found it!
We should create the header with https://api.twitter.com/1/account/verify_credentials.json and post to http://api.twitpic.com/2/upload.json! (And use GET)
NSString *fakeurl = #"https://api.twitter.com/1/account/verify_credentials.json";
NSString *oauth_header = [oAuth oAuthHeaderForMethod:#"GET" andUrl:fakeurl andParams:nil];
NSLog(#"OAuth header : %#\n\n", oauth_header);
NSString *url = #"http://api.twitpic.com/2/upload.json";
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:url]];
request.delegate = self;
[request addRequestHeader:#"User-Agent" value:#"ASIHTTPRequest"];
request.requestMethod = #"GET";
[request addRequestHeader:#"X-Verify-Credentials-Authorization" value:oauth_header];
[request addRequestHeader:#"X-Auth-Service-Provider" value:#"https://api.twitter.com/1/account/verify_credentials.json"];
NSData *imageRepresentation = UIImageJPEGRepresentation([UIImage imageNamed:#"IMG_0717.jpg"], 0.2);
if (imageRepresentation) {
NSLog(#"Pic not nil");
}
[request setData:imageRepresentation forKey:#"media"];
[request setPostValue:#"twitpic, i hate you. die painfully." forKey:#"message"];
[request setPostValue:twitPicKey forKey:#"key"];
[request setDelegate:self];
[request setDidFinishSelector:#selector(requestDone:)];
[request setDidFailSelector:#selector(requestFailed:)];
[request start];
Use GSTwitPicEngine: https://github.com/Gurpartap/GSTwitPicEngine
Using GSTwitPicEngine:
Initialize the engine with class or as needed:
self.twitpicEngine = (GSTwitPicEngine *)[GSTwitPicEngine twitpicEngineWithDelegate:self];
Find the authorization token and supply to twitpicEngine with:
[twitpicEngine setAccessToken:token];
Then to upload image and attach a text message along with it (does not post to twitter):
[twitpicEngine uploadPicture:[UIImage imageNamed:#"mypic.png"] withMessage:#"Hello world!"]; // This message is supplied back in success delegate call in request's userInfo.
To upload image only:
[twitpicEngine uploadPicture:uploadImageView.image];
Upon end of request, one of the delegate methods is called with appropriate data and information.
GSTwitPicEngineDelegate protocol specifies two delegate methods:
- (void)twitpicDidFinishUpload:(NSDictionary *)response {
NSLog(#"TwitPic finished uploading: %#", response);
// [response objectForKey:#"parsedResponse"] gives an NSDictionary of the response one of the parsing libraries was available.
// Otherwise, use [[response objectForKey:#"request"] objectForKey:#"responseString"] to parse yourself.
if ([[[response objectForKey:#"request"] userInfo] objectForKey:#"message"] > 0 && [[response objectForKey:#"parsedResponse"] count] > 0) {
// Uncomment to update status upon successful upload, using MGTwitterEngine's instance.
// [twitterEngine sendUpdate:[NSString stringWithFormat:#"%# %#", [[[response objectForKey:#"request"] userInfo] objectForKey:#"message"], [[response objectForKey:#"parsedResponse"] objectForKey:#"url"]]];
}
}
and
- (void)twitpicDidFailUpload:(NSDictionary *)error {
NSLog(#"TwitPic failed to upload: %#", error);
if ([[error objectForKey:#"request"] responseStatusCode] == 401) {
// UIAlertViewQuick(#"Authentication failed", [error objectForKey:#"errorDescription"], #"OK");
}
}
All set?
OAuth method to generate a header must be GET. Not POST.
Also url must be https://api.twitter.com/1/account/verify_credentials.json
Thanks, this helped me get it working too :) I also updated http://github.com/jaanus/PlainOAuth with working example code.