Upload Image on tumblr in iPhone - iphone

I am really stuck with this issue for many days. In my app i need to upload image on tumblr, i have tried various tutorials and updates however none of them is working for posting images on tumblr.Please help me any one if you have done this.
NSData *imageData = [NSData dataWithContentsOfFile:photo];
//stop on error
if (!imageData) return NO;
//Create dictionary of post arguments
NSArray *keys = [NSArray arrayWithObjects:#"email",#"password",#"type",#"caption",nil];
NSArray *objects = [NSArray arrayWithObjects:
tumblrEmail,
tumblrPassword,
#"photo", caption, nil];
NSDictionary *keysDict = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
//create tumblr photo post
NSURLRequest *tumblrPost = [self createTumblrRequest:keysDict withData:imageData];
[keysDict release];
//send request, return YES if successful
NSURLConnection *tumblrConnection = [[NSURLConnection alloc] initWithRequest:tumblrPost delegate:self];
if (!tumblrConnection)
{
NSLog(#"Failed to submit request");
return NO;
}
else
{
NSLog(#"Request submitted");
receivedData = [[NSMutableData data] retain];
[tumblrConnection release];
return YES;
}
-(NSURLRequest *)createTumblrRequest:(NSDictionary *)postKeys withData:(NSData *)data
{
//create the URL POST Request to tumblr
NSURL *tumblrURL = [NSURL URLWithString:#"http://api.tumblr.com/v2/blog/kashifjilani.tumblr.com/posts"];
NSMutableURLRequest *tumblrPost = [NSMutableURLRequest requestWithURL:tumblrURL];
[tumblrPost setHTTPMethod:#"POST"];
//Add the header info
NSString *stringBoundary = #"0xKhTmLbOuNdArY---This_Is_ThE_BoUnDaRyy---pqo";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",stringBoundary];
[tumblrPost addValue:contentType forHTTPHeaderField: #"Content-Type"];
//create the body
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
//add key values from the NSDictionary object
NSEnumerator *keys = [postKeys keyEnumerator];
int i;
for (i = 0; i < [postKeys count]; i++) {
NSString *tempKey = [keys nextObject];
[postBody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n",tempKey] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"%#",[postKeys objectForKey:tempKey]] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
//add data field and file data
[postBody appendData:[#"Content-Disposition: form-data; name=\"data\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[NSData dataWithData:data]];
[postBody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
//add the body to the post
[tumblrPost setHTTPBody:postBody];
return tumblrPost;
}

This works for me:
NSData *imageData = UIImageJPEGRepresentation(yourUploadImage, 0.9);
NSMutableURLRequest *aRequest = [[[NSMutableURLRequest alloc] init] autorelease];
[aRequest setURL:[NSURL URLWithString:#"https://www.tumblr.com/api/write"]];
[aRequest setHTTPMethod:#"POST"];
NSString *boundary = #"0xKhTmLbOuNdArY";
//NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[aRequest addValue:contentType forHTTPHeaderField: #"Content-Type"];
/*
now lets create the body of the post
*/
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"email\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:Tumblr_UserName_Here dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"password\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:Tumblr_Password_Here dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary]
dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"type\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"photo" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"data\"; filename=\"upload.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Transfer-Encoding: image/jpg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
if(comment available here)
{
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary]
dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"caption\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[commentString dataUsingEncoding:NSUTF8StringEncoding]];
}
// setting the body of the post to the reqeust
[aRequest setHTTPBody:body];
[NSURLConnection connectionWithRequest:aRequest delegate:self];
Now delegate of NSURLConnection
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if(connection)
NSLog(#"Success");
else
NSLog(#"Something Wrong");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
{
NSLog(#"%#",[error description]);
}

I've been struggling with this for a long time too, but I figured out how to post easily.
You can see my post for an answer to this. If you have any problem with it, I'd be glad to help.

Related

how to share image to twitter from iphone application

I'm using twitter+OAuth with MGTwitterengine in my application and successfully post a comment to twitter. But now my problem is share image to twitter using
https://upload.twitter.com/1/statuses/update_with_media.json . I searched many web sites and get source code by using this direct upload to twitter api
https://upload.twitter.com/1/statuses/update_with_media.json . here the code is below.
-(void)UploadimageToTwitter
{
//NSString *boundary = #"----------------------------991990ee82f7";
// NSURL *finalURL = [NSURL URLWithString:#"http://upload.twitter.com/1.1/statuses/update_with_media.json"];
NSString *accessTokenKey = kOAuthaccessTokenKey;
NSString *secretTokenKey = kOAuthsecretTokenKey;
NSURL *finalURL = [NSURL URLWithString:#"http://upload.twitter.com/1/statuses/update_with_media.json"];
/*if (!finalURL)
{
return nil;
}*/
OAConsumer *consumer = [[OAConsumer alloc] initWithKey:kOAuthConsumerKey secret:kOAuthConsumerSecret];
//Shearing picture on twitter with Oauth without any third party api.
OAToken *token = [[OAToken alloc] initWithKey:accessTokenKey secret:secretTokenKey]; //Set user Oauth access token and secrate key
//OAConsumer *consumer = [[OAConsumer alloc] initWithKey:ConsumerToken secret:ConsumerSecrateKey]; // Application cosumer token and secrate key
OAMutableURLRequest *theRequest = [[OAMutableURLRequest alloc] initWithURL:finalURL consumer:consumer token:token realm: nil signatureProvider:nil];
[theRequest setHTTPMethod:#"POST"];
[theRequest setTimeoutInterval:120];
[theRequest setHTTPShouldHandleCookies:NO];
// Set headers for client information, for tracking purposes at Twitter.
[theRequest setValue:DEFAULT_CLIENT_NAME forHTTPHeaderField:#"X-Twitter-Client"];
[theRequest setValue:DEFAULT_CLIENT_VERSION forHTTPHeaderField:#"X-Twitter-Client-Version"];
[theRequest setValue:DEFAULT_CLIENT_URL forHTTPHeaderField:#"X-Twitter-Client-URL"];
NSString *boundary = #"--0246824681357ACXZabcxyz";// example taken and implemented.
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[theRequest setValue:contentType forHTTPHeaderField:#"content-type"];
// NSMutableData *body = [NSMutableData dataWithLength:0];
NSMutableData *body=[NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//status
[body appendData:[[NSString stringWithFormat:#"--%#\r\n\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition:form-data; name=\"status\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"status\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[[NSString stringWithFormat:#"%#",status] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",#"Latest Uploading"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n"]dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//media
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition:form-data; name=\"media_data[]\"; filename=\"sunflower.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"media[]\"; filename=\"index.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type:application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
UIImage *image1=[UIImage imageNamed:#"sunflower.jpg"];
NSData *imageData = UIImageJPEGRepresentation(image1, 1.0);
// [body appendData:[[NSString stringWithString:[UIImageJPEGRepresentation(image, 1.0) base64EncodingWithLineLength:0]] dataUsingEncoding:NSUTF8StringEncoding]];
// [body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// [body appendData:[[NSString stringWithString:#"Honeymoon uploads image\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// --------------------------------------------------------------------------------
// modificaiton from the base clase
// our version "prepares" the oauth url request
// --------------------------------------------------------------------------------
[theRequest prepare];
NSString *oAuthHeader = [theRequest valueForHTTPHeaderField:#"Authorization"];
[theRequest setHTTPBody:body];
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"oAuthHeader = %# =",oAuthHeader);
NSLog(#"ResponsString = \n%#",responseString);
}
Using this code i'm getting responsestring is below
{"errors":[{"message":"Internal error","code":131}]}
It is a server error or my error. really do not know where i was wrong in the above code.
if anybody know answer please guide to me. your help saved my life cause i was searching the above task past three months using three kind of different api's like Twitpic, yfrog and now post/update_with_media.
NSString *status = tweetText.text;
TWRequest *sendTweet;
if(image1 == nil)
{
sendTweet = [[TWRequest alloc]
initWithURL:[NSURL URLWithString:#"https://api.twitter.com/1/statuses/update.json"]
parameters:[NSDictionary dictionaryWithObjectsAndKeys:status, #"status", nil]
requestMethod:TWRequestMethodPOST];
}
else
{
sendTweet = [[TWRequest alloc] initWithURL:[NSURL URLWithString:#"https://upload.twitter.com/1/statuses/update_with_media.json"]
parameters:[NSDictionary dictionaryWithObjectsAndKeys:status, #"status",image1,#"media" , nil]
requestMethod:TWRequestMethodPOST];
[sendTweet addMultiPartData:[tweetText.text dataUsingEncoding:NSUTF8StringEncoding] withName:#"status" type:#"multipart/form-data"];
[sendTweet addMultiPartData:UIImagePNGRepresentation(image1) withName:#"media" type:#"multipart/png"];
}
sendTweet.account = self.account;
[sendTweet performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if ([urlResponse statusCode] == 200)
{
dispatch_sync(dispatch_get_main_queue(),
^{
[self displayText:#"Tweet Done"];
});
}
else
{
NSLog(#"Problem sending tweet: %#", error);
}
}];
Hope this code works for you, it works for me, in this you can post image as well as text only. Best of luck

I am trying to post image on twitter through twitter oauth but it is giving error http 500

NSURL *finalURL = [NSURL URLWithString:#"https://api.twitter.com/1.1/statuses/update_with_media.json"];
if (!finalURL) {
return nil;
}
OAMutableURLRequest *theRequest = [[[OAMutableURLRequest alloc]
initWithURL:finalURL
consumer:self.consumer
token:_accessToken
realm:nil
signatureProvider:nil] autorelease];
NSData *imageData = UIImagePNGRepresentation(image);
[theRequest setHTTPMethod:#"POST"];
[theRequest setTimeoutInterval:120];
[theRequest setHTTPShouldHandleCookies:NO];
[theRequest setValue:_clientName forHTTPHeaderField:#"X-Twitter-Client"];
[theRequest setValue:_clientVersion forHTTPHeaderField:#"X-Twitter-Client-Version"];
[theRequest setValue:_clientURL forHTTPHeaderField:#"X-Twitter-Client-URL"];
NSString *boundary = #"--0246824681357ACXZabcxyz";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[theRequest setValue:contentType forHTTPHeaderField:#"content-type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"status\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",status] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// media
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"media[]\"; filename=\"1.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[theRequest prepare];
[theRequest setHTTPBody:body];
MGTwitterHTTPURLConnection *connection;
connection = [[MGTwitterHTTPURLConnection alloc] initWithRequest:theRequest
delegate:self
requestType:requestType
responseType:responseType];
if (!connection) {
return nil;
} else {
[_connections setObject:connection forKey:[connection identifier]];
[connection release];
}
return [connection identifier];
//Shearing picture on twitter with Oauth without any third party api.
OAToken *token = [[OAToken alloc] initWithKey:OauthAccessToken secret:OauthAccessSecrateKey]; //Set user Oauth access token and secrate key
OAConsumer *consumer = [[OAConsumer alloc] initWithKey:ConsumerToken secret:ConsumerSecrateKey]; // Application cosumer token and secrate key
// Url for upload pictures
NSURL *finalURL = [NSURL URLWithString:#"https://upload.twitter.com/1/statuses/update_with_media.json"];
OAMutableURLRequest *theRequest = [[OAMutableURLRequest alloc] initWithURL:finalURL
consumer:consumer
token:token
realm: nil
signatureProvider:nil];
[theRequest setHTTPMethod:#"POST"];
[theRequest setTimeoutInterval:120];
[theRequest setHTTPShouldHandleCookies:NO];
// Set headers for client information, for tracking purposes at Twitter.(This is optional)
[theRequest setValue:#"HomeShowAppIphone" forHTTPHeaderField:#"X-Twitter-Client"];
[theRequest setValue:#"1.0" forHTTPHeaderField:#"X-Twitter-Client-Version"];
[theRequest setValue:#"http://www.homeshowapp.com/" forHTTPHeaderField:#"X-Twitter-Client-URL"];
NSString *boundary = #"--0246824681357ACXZabcxyz"; // example taken and implemented.
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[theRequest setValue:contentType forHTTPHeaderField:#"content-type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"status\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",#"latest upload"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"media[]\"; filename=\"1.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:UIImageJPEGRepresentation([UIImage imageNamed:#"box.png"], 0.5)]];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[theRequest prepare];
NSString *oAuthHeader = [theRequest valueForHTTPHeaderField:#"Authorization"];
[theRequest setHTTPBody:body];
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest
returningResponse:&response
error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding];
https://api.twitter.com/1.1/statuses/update_with_media.json
change this url to
https://upload.twitter.com/1.1/statuses/update_with_media.json
then try it may work

NSURLConnection and NSURLConnectionDelegate work on different thread

as descripted in the title, I did some NSURLConnection like this. But I found that the delegate method couldn't get run. Anyone knows how to deal with it ?
edit:
my delegate works on the main thread, while NSURLConnection works on an operation queue. Now the case is :NSURLConnection works fine, but delegate won't run.
edit 2:
I used the class method [NSURLConnection connectionWithRequest: delegate:]
here is on my main queue
NSOperationQueue *queuePhoto = [[NSOperationQueue alloc] init];
NSInvocationOperation *invocationOperationPhotos = [[NSInvocationOperation alloc] initWithTarget:self selector:#selector(transferToServerAddimages:) object:arrayOfASection];
// [invocationOperationPhotos addObserver:self forKeyPath:#"isExecuting" options:0 context:invocationOperationPhotos];
// [invocationOperationPhotos addObserver:self forKeyPath:#"isCancelled" options:0 context:invocationOperationPhotos];
// [[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(<#selector#>) name:#"isExecuting" object:nil];
[invocationOperationPhotos setQueuePriority:NSOperationQueuePriorityHigh];
[queuePhoto addOperation:invocationOperationPhotos];
[mutableArrayPhotoQueue addObject:queuePhoto];
[invocationOperationPhotos release];
[queuePhoto release];
here is my NSURLConnnection:
- (void) transferToServerAddimages:(NSArray *) arrayToAdd
{
NSLog(#"[NSOperationQueue currentQueue]: %#", [NSOperationQueue currentQueue]);
NSString *murphoAppPrefix = [[AppDelegate sharedAppDelegate] murphoAppPrefix];
// setting up the request object now
NSString *urlString = [murphoAppPrefix stringByAppendingString:#"addPhotos.php"];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
/*
add some header info now
we always need a boundary when we post a file
also we need to set the content type
*/
// set header value , some random text that will never occur in the body
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
/*
now lets create the body of the post
*/
NSMutableData *body = [NSMutableData data];
// email part
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"email\"\r\n\r\n%#", self.trip.whoCreate.email] dataUsingEncoding:NSUTF8StringEncoding]];
// password part
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"password\"\r\n\r\n%#", self.trip.whoCreate.psw] dataUsingEncoding:NSUTF8StringEncoding]];
// image part
NSInteger subCount=0;
for (NSDictionary *aDict in arrayToAdd) {
// belonging part
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"r_whichShortTrip%d\"\r\n\r\n%#", subCount, [aDict objectForKey:#"r_whichShortTrip"]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"uniqueId%d\"\r\n\r\n%#", subCount, [aDict objectForKey:#"uniqueId"]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"createdTime%d\"\r\n\r\n%#", subCount, [aDict objectForKey:#"createdTime"]] dataUsingEncoding:NSUTF8StringEncoding]];
UIImage *imageFile = [aDict objectForKey:#"image"];
NSData *imageData = UIImageJPEGRepresentation(imageFile, 1.0);
NSString *imageName = [[URLConnect createUUID] stringByAppendingString:#".jpg"];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:
#"Content-Disposition: form-data; name=\"image%d\"; filename=%#\r\n", subCount, imageName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
UIImage *thumbnail = [aDict objectForKey:#"thumbnail"];
NSData *thumbnailData = [NSData dataWithData:UIImageJPEGRepresentation(thumbnail, 1)];
NSString *thumbnailName = [[URLConnect createUUID] stringByAppendingString:#".jpg"];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:
#"Content-Disposition: form-data; name=\"thumbnail%d\"; filename=%#\r\n", subCount++, thumbnailName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:thumbnailData]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// now lets make the connection to the web
[NSURLConnection connectionWithRequest:request delegate:self];
}
here is my delegate:
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[[[AppDelegate sharedAppDelegate] mArrayOfFailedConnection] addObject:connection];
[connection cancel];
connection = nil;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"response: %#", response);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"connection: %#", connection);
}
Actually when you set selector for operation as "transferToServerAddimages" that means when this function would executed completely your operation would be finished, also since NSUrlConnection calls its delegates on that same thread, on which it was started, so its probable that thread (OperationQueue) was finished before response arrived. If you indeed want to use NSOperationQueue then a better function to use is "sendAsynchronousRequest:queue:completionHandler:" of NSUrlConnection.
What's the delegate, the NSOperation? One possibility is your operation is calling -[connectionWithRequest:delegate:] and exit, which causes it to finish and be deleted. Put an NSLog in the operation's dealloc to see if its running.
Assuming all the operation does is NSURLConnection transations, you don't need to wrap the transaction in an NSOperation to get concurrency, since those transations are asynchronous already. But if you really want to use NSOperation (for coordination purposes etc), make it a "concurrent" one and put it on the main queue. Those kind are trickier but there are examples around.

NSData and Uploading Images via POST in iOS

I have been combing through the many many posts about uploading images via POST in iOS. Despite the wealth of information on this topic, I cannot manage to correctly upload JPEG data taken from my iPhone Simulator Photo Library.
The data, once on the server, is just a huge string of hexidecimal. Shouldn't NSData just be a byte stream? I don't get whats going on with all the hex, or why this code seems to work for everyone else.
Here is the code in question:
-(void)uploadWithUserLocationString:(NSString*)userLocation{
NSString *urlString = #"http://some.url.com/post";
// set up the form keys and values (revise using 1 NSDictionary at some point - neater than 2 arrays)
NSArray *keys = [[NSArray alloc] initWithObjects:#"auth",#"text",#"location",nil];
NSArray *vals = [[NSArray alloc] initWithObjects:self.authToken,self.textBox.text,userLocation,nil];
// set up the request object
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
//Add content-type to Header. Need to use a string boundary for data uploading.
NSString *boundary = [NSString stringWithString:#"0xKhTmLbOuNdArY"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
//create the post body
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n",boundary] dataUsingEncoding:NSASCIIStringEncoding]];
//add (key,value) pairs (no idea why all the \r's and \n's are necessary ... but everyone seems to have them)
for (int i=0; i<[keys count]; i++) {
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n",[keys objectAtIndex:i]] dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",[vals objectAtIndex:i]] dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSASCIIStringEncoding]];
}
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"image\"\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[NSData dataWithData:self.imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSASCIIStringEncoding]];
// set the body of the post to the reqeust
[request setHTTPBody:body];
// make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(returnString);
[keys release];
[vals release];
}
Thanks for your time.
This code works in my app. If you're not using ARC you'll need to modify the code to release anything alloc'ed.
// 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];
i hope this code will help some body else ...
//create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
//Set Params
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:#"POST"];
//Create boundary, it can be anything
NSString *boundary = #"------VohpleBoundary4QuqLuM1cE5lMwCy";
// 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];
//Populate a dictionary with all the regular values you would like to send.
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
[parameters setValue:param1 forKey:#"param1-name"];
[parameters setValue:param2 forKey:#"param2-name"];
[parameters setValue:param3 forKey:#"param3-name"];
// add params (all params are strings)
for (NSString *param in parameters) {
[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", [parameters objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
NSString *FileParamConstant = #"imageParamName";
NSData *imageData = UIImageJPEGRepresentation(imageObject, 1);
//Assuming data is not nil we add this to the multipart form
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:[#"Content-Type:image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
//Close off the request with the boundary
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the request
[request setHTTPBody:body];
// set URL
[request setURL:[NSURL URLWithString:baseUrl]];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
if ([httpResponse statusCode] == 200) {
NSLog(#"success");
}
}];
Take a look at Apple's SimpleURLConnections example project. You can use the PostController from there with a few modifications.
However - it's not exactly simple. The difference to the solution above is that Apple's is using a stream to stream the file to the server. That's much more memory-friendly than keeping the encoded image data around for the duration of the upload. It's also way more complicated.
NSData *imgData = UIImagePNGRepresentation(imgUser.image);
NSString *str=[NSString stringWithFormat:#"%#upload_image",appDelegate.strRoot];
NSString *urlString = [NSString stringWithFormat:#"%#",str];
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"];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"file\"; filename=\"a.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imgData]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// parameter UserId
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userid\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[appDelegate.strUserID 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];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableLeaves error:nil];
NSLog(#"%#",dict);
I see that you send multiple files in one request, correct?
From HTTP specification, you should use multipart/mixed Content-type inside embedding multipart/form-data
Example from link above:
Content-type: multipart/form-data, boundary=AaB03x
--AaB03x
content-disposition: form-data; name="field1"
Joe Blow
--AaB03x
content-disposition: form-data; name="pics"
Content-type: multipart/mixed, boundary=BbC04y
--BbC04y
Content-disposition: attachment; filename="file1.txt"

Objective C: How to upload image and text using HTTP POST?

I've successfully created two different methods where each of them can upload either an image or text. But I am having problem writing a method that can post both text and image simultaneously!
// Here's my new method witch worked fine thanx to #sgosha:
- (void) upload {
NSString *urlString = #"http://www.examplescript.com";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
// file
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 90);
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: attachment; name=\"userfile\"; filename=\".jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// Text parameter1
NSString *param1 = #"parameter text";
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"parameter1\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:param1] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// Another text parameter
NSString *param2 = #"Parameter 2 text";
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"parameter2\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:param2] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// set request body
[request setHTTPBody:body];
//return and test
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
}
//Old question:
Obviously this was too easy and didn't work! I do not get any error in the console or anything, and the image is uploaded, but the text is not sent. Any ideas?
Btw: The server-side script is a very simple php script.
Try this (EDITED):
NSMutableData *body = [NSMutableData data];
// file
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: attachment; name=\"userfile\"; filename=\".jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// text parameter
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"parameter1\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[parameterValue1 dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// another text parameter
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"parameter2\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[parameterValue2 dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// set request body
[request setHTTPBody:body];
I also wanted to upload an image along with other data in the same POST, most information about uploading images is just for uploading an image alone in one server connection, here is how I solved this.
This is the PHP
<?php
/* As you can see there are more values not only the image */
$variableOne = $_POST['variableOne'];
$variableTwo = $_POST['variableTwo'];
$variableThree = $_POST['variableThree'];
$variableFour = $_POST['variableFour'];
$variableFive = $_POST['variableFive'];
$variableSix = $_POST['variableSix'];
$variableSeven = $_POST['variableSeven'];
$variableEight = $_POST['variableEight'];
$variableNine = $_POST['variableNine'];
$variableTen = $_POST['variableTen'];
/* Our image */
$image = $_REQUEST['image'];
/* This is for trying to get a unique name for the image file, since maybe you want to store large amount of images */
$currentDate = date("Y-m-d");
$name = "" . $currentDate . microtime() . rand(0, 999) . rand(0, 999) . rand(0, 999) . ".jpg";
/*
* Here comes the image stuff
*/
if (file_exists($name)) {
echo "File already exists";
} else {
/* Decoding image */
$binary = base64_decode($image);
/* Opening image */
$file = fopen($name, 'wb');
/* Writing to server */
fwrite($file, $binary);
/* Closing image file */
fclose($file);
echo "Added";
}
}
?>
Then in Xcode copy and paste this method (taken from Creating a base-64 string from NSData)
- (NSString*)base64forData:(NSData*) theData {
const uint8_t* input = (const uint8_t*)[theData bytes];
NSInteger length = [theData length];
static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
uint8_t* output = (uint8_t*)data.mutableBytes;
NSInteger i;
for (i=0; i < length; i += 3) {
NSInteger value = 0;
NSInteger j;
for (j = i; j < (i + 3); j++) {
value <<= 8;
if (j < length) {
value |= (0xFF & input[j]);
}
}
NSInteger theIndex = (i / 3) * 4;
output[theIndex + 0] = table[(value >> 18) & 0x3F];
output[theIndex + 1] = table[(value >> 12) & 0x3F];
output[theIndex + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '=';
output[theIndex + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '=';
}
return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}
In YourViewController.h file
#interface YourViewController : UIViewController {
NSURLConnection *serverConnection;
NSMutableData *returnData;
}
This is the server connection code
NSURL *sendURL = [NSURL URLWithString:#"http://yourdomainname/imagefolder/phpscript.php"];
NSMutableURLRequest *sendRequest = [NSMutableURLRequest requestWithURL:sendURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[sendRequest setHTTPMethod:#"POST"];
[sendRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSData *imageData = UIImageJPEGRepresentation(yourImage, 1.0);
NSString *encodedString = [[self base64forData:imageData] stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"];
NSString *dataToSend = [[NSString alloc] initWithFormat:#"variableOne=%#&variableTwo=%#&variableThree=%#&variableFour=%#&variableFive=%#&variableSix=%#&variableSeven=%#&variableEight=%#&variableNine=%#&variableTen=%#&image=%#", valueOne, valueTwo, valueThree, valueFour, valueFive, valueSix, valueSeven, valueEight, valueNine, valueTen, encodedString];
[sendRequest setHTTPBody:[dataToSend dataUsingEncoding:NSUTF8StringEncoding]];
serverConnection = [[NSURLConnection alloc] initWithRequest:sendRequest delegate:self];
[serverConnection start];
Set delegate methods for server connection
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
returnData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[returnData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (connection == serverConnection) {
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Response: %#", responseString);
if ([responseString isEqualToString:#"Added"]) {
/* Make something on success */
} else {
/* Make something else if not completed with success */
}
}
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
/* Make something on failure */
}
This code works for me with 1 image and 7 other parameters using POST Request
Make sure to change your variable names plus values and also image parameter name plus 'showPhoto' which is my IBOutlet UIImageView object
'name' shows URL parameter name.
NSString *str=#"http://xxx.xxx.xxx.xx/xxxx/xxxxx/xxxxx.php?action=add_place";
NSString *urlString = [NSString stringWithFormat:#"%#",str];
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(_showPhoto.image, 90);
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"host_pic\"; filename=\"parkN.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// parameter username
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userID\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"17" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// parameter token
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"longitude\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"50.0011" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// parameter token
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"latitude\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"50.0011" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// parameter method
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"place_name\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"lahore" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//parameter method
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"place_description\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"lahore" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//parameter method
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"zip_code\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"123456" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//parameter method
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"phone_number\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"033333333" 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 reqeust
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableLeaves error:nil];
NSLog(#"%#",dict);
If you want to name the image:
NSMutableString *nombreImagen= [[NSMutableString alloc]init];
[nombreImagen appendString:#"Content-Disposition: attachment; name=\"file\"; filename=\""];
[nombreImagen appendString:#"hoy"];
[nombreImagen appendString:#".jpg\"\r\n"];
.......
[body appendData:[[NSString stringWithString:nombreImagen] dataUsingEncoding:NSUTF8StringEncoding]];