send image to twitter via oauth - ios

I am successfully able to login on twitter with oauth. Now I need to post image with status. For that I have implemented following..
-(void)shareontw{
NSString *postUrl =#"https://api.twitter.com/1.1/statuses/update_with_media.json";
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:postUrl]];
[req setValue:[oAuth oAuthHeaderForMethod:#"POST" andUrl:postUrl andParams:nil] forHTTPHeaderField:#"Authorization"];
[req setHTTPMethod:#"POST"];
NSString *boundary = #"0xKhTmLbOuNdArY---This_Is_ThE_BoUnDaRyy---pqo";
NSString *headerBoundary = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",
boundary];
[req addValue:headerBoundary forHTTPHeaderField:#"Content-Type"];
NSMutableData *myRequestData = [NSMutableData data];
NSData *imageData = UIImageJPEGRepresentation(globalimage, 0.8);
[myRequestData appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData appendData:[#"Content-Disposition: form-data; name=\"media\"; filename=\"dummy.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData appendData:[#"Content-Type: image/jpeg\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData appendData:[#"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// add it to body
[myRequestData appendData:imageData];
[myRequestData appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData appendData:[#"Content-Disposition: form-data; name=\"message\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData appendData:[#"Success\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[req setHTTPBody:myRequestData];
NSHTTPURLResponse *response;
NSError *error = nil;
NSString *responseString = [[[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error] encoding:NSUTF8StringEncoding] autorelease];
if (error) {
NSLog(#"Error from NSURLConnection: %#", error);
}
NSLog(#"Got HTTP status code from Twitter after posting profile image: %d", [response statusCode]);
NSLog(#"Response string: %#", responseString);}
But it giving me error: Response string: {"errors":[{"message":"Bad Authentication data","code":215}]}
I am unable to find the issue that what I am doing wrong here. Please if some has idea then help me out.
Thanks in advance.

thanks your above code is working fine and save a lot of time for me.i just change one line of code
this line NSData *imageData = UIImageJPEGRepresentation(globalimage, 0.8);
replace with
NSData *imageData = UIImageJPEGRepresentation(_imgView.image, 0.8);
and it's working :)

Related

How to post image on server with dictionary iOS?

I have a dictionary (dict) of some keys/values and an image. Now I want to upload image to server with dictionary. I have already try this but not getting any success. Here is my sample code--
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSData *imageData = UIImageJPEGRepresentation(image,0.5);//or you can use png representation- UIImagePNGRepresentation(image);
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"thumbnail\"; filename=\"image.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// parameter all_data
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"all_data\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",dict] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the request
[request setHTTPBody:body];
NSError *error=nil;
NSHTTPURLResponse *response=nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
I need help where is I'm going wrong.. Thanks in advance
Try out the below code:
-(void)uploadImage:(NSString *)api :(NSDictionary *)params : (UIImage *)image {
NSURL *myURL = [NSURL URLWithString:api];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:myURL];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#; charset=UTF-8", boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
NSMutableData *theBodyData = [NSMutableData data];
for (int i=0; i<[[params allKeys] count]; i++)
{
[theBodyData appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *value=#"";
value=[params objectForKey:[[params allKeys] objectAtIndex:i]];
NSString * value1=[NSString stringWithFormat:#"Content-Disposition: form-data; name=%#\r\n\r\n%#\r\n",[[params allKeys] objectAtIndex:i],value];
[theBodyData appendData:[value1 dataUsingEncoding:NSUTF8StringEncoding]];
}
[theBodyData appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[theBodyData appendData:[#"Content-Disposition: form-data; name=\"my_file1\"; filename=\"image1.jpeg\"\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[theBodyData appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
NSData *myData = UIImageJPEGRepresentation(image,0.5);
[theBodyData appendData:[NSData dataWithData:myData]];
[theBodyData appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:theBodyData];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", (int)[theBodyData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: theBodyData];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask * dataTask =[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Server Raw Response : %#",responseString);
}
}];
[dataTask resume];
}
Your code looks fine but I think you have to convert your dictionary into json string. Just Replace this line-
[body appendData:[[NSString stringWithFormat:#"%#",dict] dataUsingEncoding:NSUTF8StringEncoding]];
with
NSString *jsonStr = [[NSString alloc]initWithData:[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
[body appendData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
may be this will help you.

Upload multipart image with NSData in JSON (HTTP body)

I'm trying to upload a multipart image to server where image is converted to NSData and this NSdata is sent a parameter in HTTP body in a JSON string. Unfortunately the app crashes with this message:
**'NSInvalidArgumentException', reason: 'Invalid type in JSON write (NSConcreteMutableData)'**
I understand that the problem is with JSON. The sample code:
-(void) uploadmultipartimage {
NSString * urlimageupload = [NSString stringWithFormat:#"%#api/mobile_profiles/avatar_upload",URLPrefixCertintell];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlimageupload]];
NSData *imageData = UIImageJPEGRepresentation(_profileimage, 1.0);
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:#"PUT"];
NSString *boundary = #"unique-consistent-string";
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
// post body
NSMutableData *body = [NSMutableData data];
// add params (all params are strings)
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=%#\r\n\r\n", #"imageCaption"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", #"Some Caption"] dataUsingEncoding:NSUTF8StringEncoding]];
// add image data
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=%#; filename=imageName.jpg\r\n", #"imageFormKey"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSDictionary *jsonString = #{#"user":#{#"user_token":[[NSUserDefaults standardUserDefaults] stringForKey:#"user_token"]},#"api_key":APIKey,#"profile":body};
//***Code Crashes here**//
NSData *postData = [NSJSONSerialization dataWithJSONObject:jsonString options:0 error:nil];
//
// setting the body of the post to the reqeust
[request setHTTPBody:postData];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if(data.length > 0) {
//success
}
}];
}
You need to convert your data to NSString:
NSString *g=[[NSUserDefaults standardUserDefaults] stringForKey:#"user_token"];
if (!g)
g=#"Default Token";
NSString *base64Body = [body base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
NSDictionary *jsonString = #{#"user":#{#"user_token":g},#"api_key":APIKey,#"profile":base64Body};
Then you can always argue about the possibility of nil when reading the "user_token".
Take care,
/Anders.

Sending Image to server from IOS

In my IOS app I want to send an image to the server along with Image name using HTTP request.
I am a programmer with embedded Background so not aware with HTTP calls, and quite new to iPhone development also.
How can I accomplish this, any sample code or tutorials will be appreciated.
The better approach is to first compress your image using Image Compress Library Here and then upload it using and Networking library Liek AF Networking or you can also send it using NSUrlConnection. AFNetworking is easy to use. You can visit this page to see how to import this into your project then. Write these lines of codes.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSURL *filePath = [NSURL fileURLWithPath:#"file://path/to/image.png"];
[manager POST:#"http://samwize.com/api/poo/"
parameters:#{#"color": #"green"}
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:#"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
The easiest way for you from my point of view would be to use AFNetworking.
It'll send the image to a php page, then on the server, you build and save the image with the data sent.
Here's a basic tutorial, but lot of others on internet.
For this you can do something like this by using ASIHTTPRequest
NSURL *strUrl = [NSURL URLWithString:[NSString stringWithFormat:#"%#?action=youraction",serverUrl]];
ASIFormDataRequest *request;
request = [[[ASIFormDataRequest alloc] initWithURL:strUrl] autorelease];
[request setRequestMethod:#"POST"];
[request setTimeOutSeconds:120];
NSString *imagePAth = userImagePath;
NSArray *imageName = [userImagePath componentsSeparatedByString:#"/"];
if( userImagePath)
{
[request setFile:imagePAth withFileName:[imageName lastObject] andContentType:#"image/jpeg" forKey:#"profileImage"];
}
[request setUseCookiePersistence:NO];
[request setUseSessionPersistence:NO];
[request setDelegate:self];
[request setDidFinishSelector:#selector(requestFinished:)];
[request setDidFailSelector:#selector(requestFailed:)];
[request startAsynchronous];
- (void)requestFinished:(ASIHTTPRequest *)request
{
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
}
Use NSURLConnection, make sure that you convert images to NSData
user_id and key there are parameters.
NSURL *URL = [NSURL URLWithString:constFileUploadURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"0xLhTaLbOkNdArZ";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"user_id\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *userid = [NSString stringWithFormat:#"%li",userID];
[body appendData:[userid dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"key\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[constBackendKey dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
for (NSData *data in arrayWithFiles)
{
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"files%ld\"; filename=\"image%ld.jpg\"\r\n",[arrayWithFiles indexOfObject:data],[arrayWithFiles indexOfObject:data]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:data]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
_connection = [NSURLConnection connectionWithRequest:request delegate:self];

Ios multipart request not getting content type at server side

I am doing small project in which I need to send image file to server for that I am using multipart request.
following is my code
UIImage *resizedImage1 = [img resizedImage:CGSizeMake(90.0f, 90.0f) interpolationQuality:kCGInterpolationHigh];
NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(resizedImage1,0.8)];
NSString *urlString = #"myUrl/accounts/add_profile_image";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
// NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; image/jpeg; boundary=%#",boundary];
NSString *accessToken=[[NSUserDefaults standardUserDefaults]objectForKey:#"userAccesstoken"];
NSLog(#"access token %#",accessToken);
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
[request addValue:accessToken forHTTPHeaderField:#"auth"];
NSLog(#"request has %#",request);
// NSLog(#"imagedata has %#",imageData);
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// parameter v=1000
[postbody appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"v\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"1000\r\n"]dataUsingEncoding:NSUTF8StringEncoding]];
// mz_access_token sewt token parameter
[postbody appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"mz_access_token\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"%#\r\n",accessToken]dataUsingEncoding:NSUTF8StringEncoding]];
// image data parameter
[postbody appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithString:[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"user_image\"; filename=\"image.jpg\"\r\n\r\n"]] dataUsingEncoding:NSUTF8StringEncoding]];
//[postbody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
**[postbody appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];**
[postbody appendData:[NSData dataWithData:imageData]];
[postbody appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"body has %#",postbody);
[request setHTTPBody:postbody];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%d", [postbody length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
NSError *errorReturned = nil;
NSError *error = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
//check netwrok
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&theResponse
error:&errorReturned];
if(data)
{
//parsing json
// again converting into ns dictionary object
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &error];
//NSLog(#"post data %#",postbody);
// NSLog(#"response of web ser %# :\n %#",name,jsonArray);
NSLog(#"Response data %#",jsonArray);
// return jsonArray;
}else{
NSLog(#"error %#",error);
}
// return [[NSDictionary alloc]init];
});
This is my web service request.
I am setting content type like
[postbody appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
but still at server side I am getting #content-type =nill
*At server side we used ROR for webservice*
Please help me to solve this.
thanks in advance..
You should be setting content type by header parameters as
[request setValue:#"image/jpeg" forHTTPHeaderField:#"Content-Type"];
Please make the change.
For every multipart/form element, you need to set a proper Content-Type, e.g. the following for text-parameters:
[postbody appendData:[[NSString stringWithFormat:#"Content-Type: text/plain;charset=utf-8"] dataUsingEncoding:NSUTF8StringEncoding]];

Error 400 while uploading image from ios

I am very much new to ios.I have to upload an image to rest server from ios application. I have referred stackoverflow. But everytime the response is 400 which is bad request from client side. I am taking image from device document directory.Could some one post the exact code for image upload.Please refer the code I am using. I am not sure what to use as file name since I am downloading image from documents directory.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"POST"];
[request setURL:[NSURL URLWithString:#"urltoupload"]];
NSString *stringBoundary = #"----1010101010";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",stringBoundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition:attachment; name=\"userfile\"; filename=\"image.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:pngImageData];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *str = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"return Data ---- %#", str);
Try this:
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
// post body
NSMutableData *body = [NSMutableData data];
// add params (all params are strings)
for (NSString *param in _params) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
// add image data
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set URL
[request setURL:requestURL];
Hope it Helps!!
First convert UIImage to NSData as follows
UIImage *image = [UIImage imageNamed:#"example.png"];
NSData *data = UIImagePNGRepresentation(image);
or
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
Then form your request string
NSURL *url = [NSURL URLWithString:serverURL];
//Time out interval need to be tuned
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: [requestString dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
if (!data)
{
NSLog(#"Error downloading data: %#", error);
return;
}
NSError *error1;
NSDictionary *theDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error1];
DLog(#"Data received :%#", theDict);
}];

Resources