I currently upload images in the background to a server like this (the names get changed at the server to something better).
buildURL = [buildURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *imageData = UIImageJPEGRepresentation(imageToUpload, 1.0); //change Image to NSData
if (imageData != nil)
{
NSString *filenames = [NSString stringWithFormat:#"imagename"]; //set name here
NSLog(#"%#", filenames);
NSString *urlString = buildURL;
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];
[request addValue: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=\"filenames\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[filenames dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"userfile\"; filename=\".jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[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
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Returned From Image Upload : %#",returnString);
}];
}
This works fine, I can see the images finish in the background no problem. The thing is I want to change this to use NSURLSession and the delegate didSendBodyData so that I can monitor the upload.
I have found a load of information about the download but none really about upload. I have tried to do this with the request BUT the completion block NEVER happens.. I have also tried using uploadTaskWithStreamedRequest but I can not get the delegate to happen...
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];
NSURLSessionDataTask *uploadTask = [session uploadTaskWithRequest:request fromData:imageData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSLog(#"Image Uploaded ------------");
}];
[uploadTask resume];
I also found this StackOverflow 19985353 which seems to highlight some problems but I could really do with some example code. The image is picked from imagePicker if that helps.
I also tried both the answers here StackOverflow 19099448 but neither of them worked, again the block never executed. Is there something fundamental I am doing wrong with NSURLSession, a framework maybe! I also note I have no idea about the HTTP body which I have tried to play with but no luck.
Okay I did not realise that Session only works in iOS7 and above. To this end I have done a test and if iOS6 then I use NSURLConnection. The problem is I cannot get progress status from this (with the session I have an upload bar).
If anyone has any ideas about an upload progress bar using NSURLConnection then I would love to hear about it.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:_urlToUpload];// create request
[request setHTTPMethod:#"POST"];// request type
[request setTimeoutInterval:60];
[request setValue:#"application/octet-stream" forHTTPHeaderField: #"Content-Type"];// content type
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];// configuration
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];// session
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromFile:file completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { }
Use the delegates
#pragma mark -
#pragma mark Session Upload Delegate Methods
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {
float status = (double)totalBytesSent / (double)totalBytesExpectedToSend;
[[MTFileStreamer sharedFileStreamer] setCurrentStatus:status];
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
NSLog(#"%s", __PRETTY_FUNCTION__);
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response
newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler {
NSLog(#"%s", __PRETTY_FUNCTION__);
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {
NSLog(#"%s", __PRETTY_FUNCTION__);
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task needNewBodyStream:(void (^)(NSInputStream *bodyStream))completionHandler {
NSLog(#"%s", __PRETTY_FUNCTION__);
}
Related
I'm trying to update my code from NSUrlConnection to NSUrlSession. The app is running fine, no errors, but the token is never uploaded to the MySQL database... I've really no idea? Should I implement delegates or am I doing something basic stuff very wrong here? :-)
NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:#"deviceToken"];
//Information is only uploaded to SQLite database if 'deviceToken' is not null
if ([deviceToken length] > 0) {
NSURL *url = [NSURL URLWithString:#"http://sampleUrl.com/do.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *varString = [NSString stringWithFormat:#"deviceToken=%#", deviceToken];
NSData *requestData = [varString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
/*NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:requestData completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
//Handle
}];*/
//NSURLSessionUploadTask *uploadTask2 = [session uploadTaskWithStreamedRequest:request];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
//Handle
}];
[dataTask resume];
Any ideas?
Thanks and regards,
Tom
I solved the problem:
NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:#"deviceToken"];
//Information is only uploaded to SQLite database if 'deviceToken' is not null
if ([deviceToken length] > 0) {
// Create URL and URLRequest
NSURL *url = [NSURL URLWithString:#"http://url.com/something.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//Create the body
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *varString = [NSString stringWithFormat:#"deviceToken=%#", deviceToken"]];
// Create POST parameters and add it to HTTPBody
[request setHTTPMethod:#"POST"];
[request setHTTPBody: [varString dataUsingEncoding:NSUTF8StringEncoding]];
// Set up a simple and asynchronous NSURLSession to send data to the php
// Set up the session configuration and header data
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
[config setRequestCachePolicy:NSURLRequestUseProtocolCachePolicy];
[config setHTTPAdditionalHeaders:#{
#"Accept" : #"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
#"Content-Type" : #"application/x-www-form-urlencoded",
#"Content-Length" : [NSString stringWithFormat:#"%lu", (unsigned long)[[varString dataUsingEncoding:NSUTF8StringEncoding] length]]
}];
// Create the session and the task
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
if (error)
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
if (response)
{
NSLog(#"response description: %#", response.description);
[prefs setBool:YES forKey:#"tokenSent"];
}
if (data)
NSLog(#"data description: %#", data.description);
}];
// Start the task
[task resume];
}
Regards,
Tom
I have written a REST service that serves up some data. It is passcode protected.
I am trying to write a background process that will grab the data and stuff it into a sqlLite db I have in the app.
I did this initially without authentication using :
- (void) callWebService {
dispatch_sync(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:
scoularDirectoryURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
This worked fine but I don't think I can add authentication to that. If I can I would just use that.
What I am looking for is a nice, simple explanation of NSURLSession using user/password authentication.
I think your question is vague and underspecified. That said, here's one solution, from here:
-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)( NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
if (_sessionFailureCount == 0) {
NSURLCredential *cred = [NSURLCredential credentialWithUser:self.userName password:self.password persistence:NSURLCredentialPersistenceNone];
completionHandler(NSURLSessionAuthChallengeUseCredential, cred);
} else {
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
}
_sessionFailureCount++;
}
I strongly recommend that you read and re-read the Apple docs on this.
For me the following code works:
NSString *userName=#"user:";
NSString *userPassword=#"password";
NSString *authStr= [userName stringByAppendingString:userPassword];
NSString *url=#"http://000.00.0.0:0000/service.json";
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat: #"Basic %#",[authData base64EncodedStringWithOptions:0]];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
NSDictionary *theDictionary = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
NSDictionary *host = [theDictionary objectForKey : #"host"];
// json nested
self.label.text = [host objectForKey:#"key1"];
self.label.text = [host objectForKey:#"key2"];
regards
Very first question here...
I'm desperately trying to upload a photo to Facebook from my Mac OS App (cocoa), using an HTTP POST request.
Using the "https://graph.facebook.com/me/photos?access_token=....." followed by "source=MyURLOnline.jpg", it works great, but I need to upload the DATA, not a link of an image already on the Web...
So I'm switching "feed" to "photos", and the URL by the RAW data of my NSImage (and maybe the "source=" to "image=" ?).
But : I set the header of my request to "multipart/form-data, boundary=%AaB03x" and add some "\r\n" and "Content-Type: image/jpeg\r\n\r\n" etc to the body, but the only thing I get is the error "(#324) Requires upload file"...
I have a few years of experience on Cocoa but don't know anything about HTTP request, and especially what is the Graph API expecting, so I've read all Facebook help I found, would have loved to find an example as I'm sure I make several mistakes, but I'm wondering if it is just possible at all.
ANY help appreciated !
UPDATE:
Thank you very much Anvesh.
If you know that I should POST a JSON then I spent my day trying to figure out how to do that, but no success yet.
Here is my code, if I POST a "source=URLOnline.jpg" to the "feed" (and remove the HTTPHeader and the Body), my image shows on my wall. With my image data to the "photos", the only hint I receive is the #324 error...
Wondering where I can find out what I should exactly write in the HTTPBody.
// Convert NSImage to data
NSImage * MyIm = [[NSImage alloc] initWithContentsOfURL:[MyLogoPath URL]];
NSData *imageData = [MyIm TIFFRepresentation];
NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:imageData];
imageData = [imageRep representationUsingType:NSPNGFileType properties:nil];
// HTTP Request with access token
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
NSString * MyStr = [#"https://graph.facebook.com/me/photos?access_token=" stringByAppendingString:FacebookToken]; // feed?access_token
[request setURL:[NSURL URLWithString:MyStr]];
[request setHTTPMethod:#"POST"];
const char *bytes = [[NSString stringWithFormat:#"&image="] UTF8String];
// const char *bytes = [[NSString stringWithFormat:#"&source=http://www.google.ca/intl/en_ALL/images/logos/images_logo_lg.gif"] UTF8String];
NSMutableData * MyData = [NSMutableData dataWithBytes:bytes length:strlen(bytes)];
// HTTP Header
NSString * boundary = [NSString stringWithFormat:#"AaB03x"];
NSString * contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
// HTTP Body
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: attachment; name=\"image\"; filename=\".jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[MyData appendData:body];
[request setHTTPBody:MyData];
[[FacebookView mainFrame] loadRequest:request];
// NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:MyURLRequest delegate:self];
// [connection start];
// [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
// }];
Thank you Anvesh, with your help and a Cocoa post about HTTP POST, I finally managed to create my NSURLRequest to upload my NSImage to Facebook.
I hope it will save a lot of trouble to people connecting their Mac App to Facebook, as there is no SDK.
// Convert the NSImage to NSData
NSData *imageData = [MyIm TIFFRepresentation];
NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:imageData];
imageData = [imageRep representationUsingType:NSPNGFileType properties:nil];
// Create the URL request with the access token
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
NSString * MyStr = [#"https://graph.facebook.com/me/photos?access_token=" stringByAppendingString:FacebookToken];
[request setURL:[NSURL URLWithString:MyStr]];
[request setHTTPMethod:#"POST"];
// Create the header and body of the request with all those settings
NSMutableData *body = [NSMutableData data];
NSString * boundary = [NSString stringWithFormat:#"Random_Boundary_Chars"];
NSString *contentType2 = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType2 forHTTPHeaderField:#"Content-Type"];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: attachment; name=\"image\"; filename=\".tiff\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
// [[FacebookView mainFrame] loadRequest:request];
// Send the request, not showing in the webview
NSData * returnData = [ NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil ];
NSString * returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Returned Json: %#", returnString);
//NSImage is now on Facebook's wall and we got the ID returned.
In my current xcode project, I need to send parameter values to a url and need to retrieve an xml file based on the parameter values sent.
I tried the below code but it's not working:
(IBAction)myButtonClick:(id)sender
{
NSURL *oRequestURL =
[NSURL URLWithString:#"http://xyz .com/air/1.0/search?from=MAA&to=CJB&depart-date=2012-06-30&adults=2&children=2&infants=1&way=one&cabin-type=Economy&sort=asc"];
NSMutableURLRequest *oRequest = [[[NSMutableURLRequest alloc]init]autorelease];
[oRequest setHTTPMethod:#"POST"];
[oRequest setURL: oRequestURL];
NSMutableData *oHttpBody = [NSMutableData data];
[oHttpBody appendData:[#"This is HTTP Request body" dataUsingEncoding:NSUTF8StringEncoding]];
[oRequest setValue:[oHttpBody length] forHTTPHeaderField:#"Content-Length"];
NSError *oError = [[NSError alloc]init];
NSHTTPURLResponse *oResponseCode = nil;
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:oRequest returningResponse:oResponseCode error:oError];
if ([oResponseCode statusCode]> 200) {
NSLog(#"Status code is greater than 200");
}
NSString *strResult=[[NSString alloc]initWithData:oResponseData encoding:NSUTF8StringEncoding];
NSLog(#"The result is %s",strResult);
}
I have searched many sites and books but could not find a solution.
Would be of great help if a link to a tutorial or some other useful resource can be provided. Appreciate your great help.
Thank You.
Hi,
I have found the solution. The code is as below. Hope it helps someone else:)
- (IBAction)myButtonPressed:(id)sender
{
NSString *urlAsString = #"http://api.abc.com/air/1.0/search?from=MAA&to=CJB&depart-date=2012-09-30&adults=2&children=2&infants=1&way=one&cabin-type=Economy&sort=asc";
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setValue:#"2193141de2g7e2a34bb19bc3aa52b3b5" forHTTPHeaderField:#"X-XX-API-KEY"];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:#"GET"];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection
sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length]>0 &&
error == nil)
{
NSString *html = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"HTML = %#", html);
}
else if ([data length]== 0 && error==nil) {
NSLog(#"Nothing was downloaded");
}
else if (error!= nil) {
NSLog(#"Error occured = %#", error);
}
}];
}
I’ve been trying to follow some examples for uploading data to a website. I want to save the message as a .txt file. Any ideas what to do here?
- (IBAction)sendSerializedGreeting:(id)sender;
{
NSString *message;
message =#"Here we go for a test message.";
// Show a loading indicator
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSString *greetingURL = [NSString stringWithFormat:#"http://www.site.com/upload.php"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:greetingURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSDictionary *headerFieldsDict = [NSDictionary dictionaryWithObjectsAndKeys:#"text/xml; charset=utf-8", #"Content-Type", nil];
[theRequest setHTTPBody:[message dataUsingEncoding:NSUTF8StringEncoding]];
[theRequest setAllHTTPHeaderFields:headerFieldsDict];
[theRequest setHTTPMethod:#"POST"];
// create the connection with the request and start loading the data
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection == nil)
{
NSLog(#"Failed to create the connection");
}
}
Here is the upload.php file. I’m assuming the issue is with this but not sure. I don’t know where the filename gets set in the example above. This code was used from somewhere else.
<?php
$uploaddir = './'; //Uploading to same directory as PHP file
$file = basename($_FILES['userfile']['name']);
$uploadFile = $file;
$randomNumber = rand(0, 99999);
$newName = $uploadDir . $randomNumber . $uploadFile;
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
echo "Temp file uploaded.";
} else {
echo "Temp file not uploaded.";
}
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $newName)) {
}
?>
I am sending a image to server through this code .... use for your text file or any type of multiform data
NSString *strUrl=#"http://www.site.com/upload.php";
NSLog(#"%#",strUrl);
NSURL *url=[NSURL URLWithString:strUrl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:130.0];
// file name of user picture
// I am sending a image to server
NSString *fileName=[[eMailTxtField.text stringByReplacingOccurrencesOfString:#"#" withString:#"-"] stringByAppendingString:#".jpg"];
//image data
UIImage *userImage=imgUser.image;
NSData *imageData =UIImageJPEGRepresentation(userImage, 90);
NSMutableData *myRequestData = [[NSMutableData alloc] init];
[myRequestData appendData:[NSData dataWithBytes:[postData UTF8String] length:[postData length]]];
NSString *boundary = [NSString stringWithString:#"--"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
[myRequestData appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"uploadfile\"; filename=\"%#\"\r\n", fileName] dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[myRequestData appendData:[NSData dataWithData:imageData]];
[myRequestData appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[ request setHTTPMethod: #"POST" ];
[ request setHTTPBody: myRequestData ];
NSURLResponse *response;
NSError *error;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse:&response error:&error];
if (!error && returnData) {
NSString *content = [NSString stringWithUTF8String:[returnData bytes]];
[self registerWithJsonString:content];
}
else{
[self showServerNotFoundError];
}