Trying to upload image from iPhone to server using ASIFormDataRequest - iphone

I'm trying to use ASIFormDataRequest to send a photo image from my
iPhone app to my server.
When I do so, the server sends back an error
message saying, "must be an image file," implying that there is
something wrong with the formatting of my image. (Of course, that
might not be the problem...but it's a good place to start.) I know
there's no "problem," per se, on the server, because a previous
approach I used (non-ASIHTTPRequest-based) worked fine.
Here's my iPhone code:
ASIFormDataRequest* request = [ASIFormDataRequest requestWithURL:
[NSURL URLWithString:photoUploadURLString]];
request.username = self.username;
request.password = self.password;
[request setPostValue:self.place.placeId forKey:#"place_id"];
NSData* jpegImageData = UIImageJPEGRepresentation(self.photo,
PHOTO_JPEG_QUALITY);
NSString* filename = [NSString stringWithFormat:#"snapshot_%#_
%d.jpg", self.place.placeId, rand()];
[request setData:jpegImageData withFileName:filename
andContentType:#"image/jpeg" forKey:#"snapshot[image]"];
request.uploadProgressDelegate = self.progressView;
[request startSynchronous];
Anyone see anything wrong with this? (I'm fairly new to this stuff, so
there could be something obvious I'm missing.)
Thanks very much.

Have you ever try addData instead of setData, It worked on my solution.
[request addData:jpegImageData withFileName: filename andContentType:#"image/jpeg" forKey:#"photos"];
Edit: By the way, which server side are you using ?
Your problem might be inside of the your key forKey:#"snapshot[image]"] try to dummy variable key like forKey:#"mysnapshot"]
Hope this helps

Related

GET http requests In Objective C

I have the following code in objective c that is supposed to make a GET http request to my website which in turn will submit something into my MySQL database...
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.website.com/VideoPush/plist/urlTransfer.php"]];
[request setHTTPMethod:#"GET"];
NSString *post =[[NSString alloc] initWithFormat:#"videoID=%#",videoURL];
[request setHTTPBody:[post dataUsingEncoding:NSUTF8StringEncoding]];
Note: I'm a total beginner to http requests with Objective c so I realize I could be missing something obvious...
Now if I run the following url in my browser...
http://www.website.com/VideoPush/plist/urlTransfer.php?videoID=hhklskdjsad
Then something gets entered into the database, but not when I'm using objective c. Also what is the difference between GET and POST when you make requests like this (since the user doesn't see the url anyways)?
ALSO: Am I allowed to pass a url (still a nsstring with /'s though) as the videoURL variable above
You've tried to set the body of a GET request, which makes no sense. What you probably want is:
NSString *urlString = [NSString stringWithFormat:#"http://www.website.com/VideoPush/plist/urlTransfer.php?videoID=%#", videoURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
... the rest of your method ...
You should probably go and have a read up about what a GET and a POST is and why I said it makes no sense to have a body in a GET request.
ALSO: Am I allowed to pass a url (still a nsstring with /'s though) as the videoURL variable above
No, you will need to URL encode anything in the query string. You can use CFURLCreateStringByAddingPercentEscapes to do this for you.

No request information sent with ASIHTTPRequest

I am experiencing an issue on iOS 4.3+ with ASIHTTPRequest where a request is fired but no data (Request methed, url, headers, etc) reaches the server. The connection times out because it never hears back.
The server hears the empty request (after some delay), then hears a valid request which is of course never reported to higher level code because the connection has timed out. This is all kind of strange because the request was not configured to resend data.
Often this happens after the app has been pushed to the background for some time (15 min or more) and the phone has been allowed to sleep.
My configuration of the request is as follows:
NSMutableData *postData = nil;
NSString *urlString = [NSString stringWithFormat:#"%#%#",[self baseURL],requestPath];
OTSHTTPRequest *request = [OTSHTTPRequest requestWithURL:[NSURL URLWithString:urlString]];
[request setCachePolicy:ASIFallbackToCacheIfLoadFailsCachePolicy];
[request setTimeOutSeconds:45];
//Set up body
NSString *queryString = [self _RPcreateQueryString:query];
if ([queryString length]>0) {
if(method == RPAsyncServerMethodPost || method == RPAsyncServerMethodPut){
postData = [[[queryString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES] mutableCopy] autorelease];
}else{
NSURL *url = [NSURL URLWithString:[urlString stringByAppendingFormat:#"?%#",queryString]];
[request setURL:url];
if (!url) return nil; //url String malformed.
}
}
// ... ///
// method setting stripped for brevity
[request addRequestHeader:#"Content-Type" value:#"application/x-www-form-urlencoded"];
if(headers){
for (NSString* head in headers) {
if ([[headers valueForKey:head] isKindOfClass:[NSString class]])
[request addRequestHeader:head value:[headers valueForKey:head]];
}
}
[request addRequestHeader:#"Content-Length" value:postLength];
[request setPostBody:postData];
OTSHTTPRequest is simply a subclass of ASIHTTPRequest that contains properties for a string tag, a pretty description, and other bling for use by consuming objects and does not override any ASI stuff.
Can anyone shed a light on why/how ASI could open a connection and then send absolutely nothing for minutes at a time?
Edit: Just to clarify. The connections DO make contact with the server, it just never sends any data through the connection from what my server logs can tell. This seems to always happen on app wake and effects all connections including NSURLConnections spawned by MapKit. the whole app just seems to loose its marbles.
I also see a bunch of background tasks ending badly right before this, but i can never catch them while in the debugger.
It doesn't look like you are starting your request based on the code that you have provided. Try call the -[startSynchronous] or -[startAsynchronous] methods of your OTSHTTPRequest object after you are done setting its various properties.
Are you setting the delegate, either I overlooked it or you stripped it out.
I didnt want to say anything till a few days passed with out the issue. The solution in this case was very obscure.
It appears the version of TestFlight i was using has a bug in it that may have contributed to this issue. Since its removal i have not experienced the issue.

Post Data format is diffrent then what I needed

I am having a simple problem while making a request to server for updating a name field. I need to post some data in this format:-
{"api_token"=>"api", "device_token"=>"device", "user"=>{"name"=>"mohit"}, "id"=>"4"}
But when i am trying to post something its posting in this format:-
{"user"=>"(\n {\n name = ChangeName;\n }\n)", "api_token"=>"api", "device_token"=>"device", "id"=>"4"}
I am not able to figure out how to change my code to generate proper request. Here is the code that I am using.
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:#"http://localhost:3000/users/4?api_token=api&device_token=device"]];
NSMutableDictionary *dict= [NSMutableDictionary dictionaryWithObjectsAndKeys: #"Mike",#"name", nil];
NSArray *array=[[NSArray alloc]initWithObjects:dict, nil];
[request setPostValue:array forKey:#"user"];
[request setRequestMethod:#"PUT"];
[request setDelegate:self];
[request setDidFinishSelector:#selector(requestFinished:)];
[request startAsynchronous];
Please let me know if i need to post some more code fragments.
ASIFormDatRequest setPostValue:forKey: wants strings, not structures. It ends up calling description to convert them to strings and you're getting the printable description of an array with a dictionary in it.
Rails uses a naming scheme that allows you to simulate a hierarchy in a flat space using a field naming convention detailed at http://guides.rubyonrails.org/form_helpers.html. You should read that and understand the html produced by the form helpers.
Try:
[request setPostValue:#"mohit" forKey:#"user[name]"];
and rails will unpack it into the proper kind of collection on the server.

Sending multiple arguments to Drupal REST Services from iPhone

I am trying to access a Drupal service that takes more than one argument. The method is views.get and the server I'm using is REST 6.x-2.0-beta3. I am retrieving data from the server for 0 or 1 arguments with no trouble. Any argument after the first, however, is simply ignored. I have tested the view on the Drupal site, and it limits results correctly for every argument passed.
I've come to the conclusion that my problem must be the formatting, but I've tried nearly everything I can think of, not to mention a dozen suggestions I've found while Googling for an answer. My code is below:
responseData = [[NSMutableData data] retain];
NSMutableString *httpBodyString =[[NSMutableString alloc] initWithString:#"method=views.get&view_name=apps&args=1&display_id=default"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://drupalserver.com/services/rest/service_views/get.json"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[httpBodyString dataUsingEncoding:NSUTF8StringEncoding]];
[httpBodyString release];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
I have tried:
args=1,2
args=[1,2]
args="1,2"
args=["1","2"]
and several others along that vein. Does anyone know the proper way to do this?
You should considering using, https://github.com/workhabitinc/drupal-ios-sdk

I need the correct syntax for the setValue:forHTTPHeaderField: method on NSMutableURLRequest

I am pulling my hair out trying to conjure up the correct syntax to set the HTTP header information do a byte-range load from an HTTP server.
This is the offending method on NSMutableURLRequest
- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field
This is how I am using this method to load the first 512 byte of a URL request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:#"0-512\r\n" forHTTPHeaderField:#"Range"];
So far it is ignored and I always receive the entire data payload. I just want the range of bytes specified (0 - 512). Can someone please relieve my headache?
Update:
I have used curl to confirm that my web server supports byte ranges thusly:
curl --range 0-2047 http://www.somewhere.com/humungodata.dat -o "foobar"
The file size of foobar is 2048
Cheers,
Doug
Problem solved.
By adding additional header fields the code immediately worked correctly. Why? Dunno. But it works:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:#"keep-live" forHTTPHeaderField:#"Connection"];
[request setValue:#"300" forHTTPHeaderField:#"Keep-Alive"];
[request setValue:#"bytes=0-2047" forHTTPHeaderField:#"Range"];
Your original code was wrong in the setValue line, it should be #"bytes=0-512". In your followup, you used the correct string, so the other headers should not be needed.
What you have there should be the correct way to add a header value to a URL request, however i thought only posts got header values, maybe im wrong, have you tried doing this on other enviroments and gotten it to work? Maybe take out the \r\n?