Upload xml file to server - ios

I am trying to upload a file like this:
- (NSString *)uploadWithTarget:(NSString *)url andFileData:(NSData *)file andMD5Checksum:(NSString *)checksum andFileName:(NSString *)name
{
uploadFinished = false;
NSString *response = #"";
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: self delegateQueue: [NSOperationQueue mainQueue]];
NSURL * urll = [NSURL URLWithString:url];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:urll];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest addValue:checksum forHTTPHeaderField:#"Md5Hash"];
[urlRequest addValue:#"Keep-Alive" forHTTPHeaderField:#"Connection"];
NSString *boundary = #"*****";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[urlRequest 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:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"%#\"\r\n", name] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/xml\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:file]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[urlRequest setHTTPBody:body];
NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithRequest:urlRequest];
//[dataTask resume];
NSURLSessionUploadTask *uploadTask = [defaultSession
uploadTaskWithRequest:urlRequest
fromData:file
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error)
{
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
if (!error && httpResp.statusCode == 200) {
NSLog(#"Request body %#", [[NSString alloc] initWithData:[urlRequest HTTPBody] encoding:NSUTF8StringEncoding]);
} else {
}
}];
[uploadTask resume];
return response;
}
But my Server always responds File not Found! Is that not correct code?!

- (void) uploadLog :(NSString *) filePath
{
NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];
NSString *urlString =[NSString stringWithFormat:#"http://www.yoursite.com/accept.php"];
// to use please use your real website link.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"_187934598797439873422234";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
[request setValue:#"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:#"Accept"];
[request setValue:#"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/536.26.14 (KHTML, like Gecko) Version/6.0.1 Safari/536.26.14" forHTTPHeaderField:#"User-Agent"];
[request setValue:#"http://google.com" forHTTPHeaderField:#"Origin"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"Content-Length %d\r\n\r\n", [data length] ] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"picture\"; filename=\"%#.png\"\r\n", #"newfile"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:data]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request addValue:[NSString stringWithFormat:#"%d", [body length]] forHTTPHeaderField:#"Content-Length"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
}
And here is the php part that works for me.
<?php
$target_path = "./uploads/";
$target_path = $target_path . basename( $_FILES['picture']['name']);
if(move_uploaded_file($_FILES['picture']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['picture']['name'])." has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>

Related

How to post multipath image in Objective C using NSURLSession and NSJSONSerialization?

NSString *BoundaryConstant = #"----------V2ymHFg03ehbqgZCaKO6jy";
// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
NSString* FileParamConstant = #"picture";
// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:strUrl];
// 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=%#", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
// post body
NSMutableData *body = [NSMutableData data];
Is FileParamConstant name is backend side multipath image folder name? It is same name I have set but why it's not working?
Below code is perfectly working , and yes FileParamConstant is the name of your backend side folder where image is store:
NSMutableDictionary * dictParam = [[NSMutableDictionary alloc]init];
[dictParam setObject:[dlf objectForKey:KEY_LOGIN_USER_ID] forKey:#"userId"];
[dictParam setObject:FirstNametextField.text forKey:#"first_name"];
[dictParam setObject:LastNametextField.text forKey:#"last_name"];
[dictParam setObject:MobileNumbertextField.text forKey:#"contact_no"];
[dictParam setObject:AddressTetField.text forKey:#"address"];
[dictParam setObject:photoselect forKey:#"is_upload"];
NSString *strUrl=[NSString stringWithFormat:#"%#update_worker_profile?",WEB_SERVICE_URL];
// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = #"----------V2ymHFg03ehbqgZCaKO6jy";
// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
NSString* FileParamConstant = #"picture";
// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:strUrl];
// 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=%#", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
// post body
NSMutableData *body = [NSMutableData data];
// add params (all params are strings)
for (NSString *param in dictParam) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", [dictParam objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
CGSize newSize = CGSizeMake(200.0f, 200.0f);
UIGraphicsBeginImageContext(newSize);
[Workerprofileimage.image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData = UIImageJPEGRepresentation(newImage, 1.0);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] 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]];
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
NSString *postLength = [NSString stringWithFormat:#"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setURL:requestURL];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSMutableDictionary *dataResponse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(#"dataResponds=%#",dataResponse);
dispatch_async(dispatch_get_main_queue(), ^{
if ([[dataResponse objectForKey:#"status"] isEqualToString:#"success"]) {
}else{
NSLog(#"no");
}
});
}] resume];
}

Status code:413 - File greater than 1 MB not uploaded on iOS 10

I have implemented code for nginx upload file to server using NSURLSession for speed test. This is working properly on iOS 8 but on iOS 10 it is giving status code 413 (request entity too large).
File size is approx 30MB, If file size is less then 1MB it's working properly. Here is my code
NSString *BoundaryConstant = #"----------V2ymHFg03ehbqgZCaKO6jy";
NSString* FileParamConstant = #"file";
NSURL* requestURL = [NSURL URLWithString:kPathForUploadCheck];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:600];
[request setHTTPMethod:#"POST"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
NSString *path = [[NSBundle mainBundle] pathForResource:#“myfile” ofType:#"psd"];
NSData *imageData22 = [NSData dataWithContentsOfFile:path];
NSString *base64String = [imageData22 base64EncodedStringWithOptions:0];
NSData *imageData = [base64String dataUsingEncoding:NSUTF8StringEncoding];
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] 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]];
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setURL:requestURL];
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *backgroundSeesion = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate:self delegateQueue: [NSOperationQueue mainQueue]];
NSURL* tempUrl = [NSURL fileURLWithPath:path];
uploadTask = [backgroundSeesion uploadTaskWithRequest:request fromFile:tempUrl];
uploadTask = [backgroundSeesion uploadTaskWithRequest:request fromData:imageData];
[uploadTask resume];

How can I send a multipart HTTP request on iOS?

I am trying to upload a photo onto a server on my iOS App using multipart method. However, I can't seem to get it to work. I am getting the error:
At least one of the pre-conditions you specified did not hold. Bucket POST must be of the enclosure-type multipart. I've looked this error and can't seem to figure out how I can solve this problem on my end. The Android version of the app works so the API should not be the problem?
Here is my code:
//photo file
NSData *data = [[NSFileManager defaultManager] contentsAtPath:filePath];
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:uploadInfo.key forKey:#"key"];
[_params setObject:uploadInfo.aaki forKey:#"AWSAccessKeyId"];
[_params setObject:uploadInfo.acl forKey:#"acl"];
[_params setObject:uploadInfo.policy forKey:#"policy"];
[_params setObject:uploadInfo.signature forKey:#"signature"];
[_params setObject:uploadInfo.success_action_status forKey:#"success_action_status"];
[_params setObject:#"image/jpeg" forKey:#"Content-Type"];
NSURL* requestURL = [NSURL URLWithString:uploadInfo.path];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
for (NSString *param in _params) {
[body appendData:[[NSString stringWithFormat:#"%#", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
if (data) {
[body appendData:data];
}
[request setHTTPBody:body];
[request setURL:requestURL];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);
Try as below.
//photo file
NSData *data = [[NSFileManager defaultManager] contentsAtPath:filePath];
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:uploadInfo.key forKey:#"key"];
[_params setObject:uploadInfo.aaki forKey:#"AWSAccessKeyId"];
[_params setObject:uploadInfo.acl forKey:#"acl"];
[_params setObject:uploadInfo.policy forKey:#"policy"];
[_params setObject:uploadInfo.signature forKey:#"signature"];
[_params setObject:uploadInfo.success_action_status forKey:#"success_action_status"];
NSURL* requestURL = [NSURL URLWithString:uploadInfo.path];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[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"];
NSMutableData *body = [NSMutableData data];
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]];
}
NSString *FileParamConstant = #"image"; // Key of webservice in which you need to send image
// add image data
if (data) {
[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:data];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
//Close off the request with the boundary
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setURL:requestURL];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
Try with another simple code.
NSDictionary *aParams =#{}; //your param dictionary here
UIImage *aImage = [UIImage imageNamed:#"your image here"]; //set yout image here
NSString *aStrParamName = #"image parameter name here";// set parameter name of image here
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"uploadInfo.path"]];// url here
[request setHTTPMethod:#"POST"];
[request setTimeoutInterval:30];
NSString *uuidStr = [[NSUUID UUID] UUIDString];
[request addValue:[NSString stringWithFormat:#"multipart/form-data; boundary=%#", uuidStr] forHTTPHeaderField:#"Content-Type"];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
NSData *imagedata = UIImageJPEGRepresentation(aImage, (CGFloat)0.6);
NSData *fileData = UIImagePNGRepresentation([UIImage imageWithData:imagedata]);
NSData *data = [self createBodyWithBoundary:uuidStr withDictData:aParams data:fileData filename:aStrParamName];
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSAssert(!error, #"%s: uploadTaskWithRequest error: %#", __FUNCTION__, error);
// parse and interpret the response `NSData` however is appropriate for your app
NSString *aStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"ResponseString:%#",aStr);
NSMutableDictionary *aMutDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"responce:%#",aMutDict);
});
}];
[task resume];
also add below method
- (NSData *)createBodyWithBoundary:(NSString *)boundary withDictData:(NSDictionary *)aDict data:(NSData*)data filename:(NSString *)paramName
{
NSMutableData *body = [NSMutableData data];
if (data) {
//only send these methods when transferring data as well as username and password
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"%#\"\r\n", paramName,#"image.png"] dataUsingEncoding:NSUTF8StringEncoding]];
#warning if you have to chane name of image then change. if there is any error then chane other wise go as it is..
[body appendData:[[NSString stringWithFormat:#"Content-Type: %#\r\n\r\n", #"image/png"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:data];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}
for (NSString *aKey in aDict.allKeys) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n%#\r\n", aKey,aDict[aKey]] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
return body;
}

upload image to web service from database using xcode

I want to upload a image from phone to web service my link is like below as sample
"http://sample.com/upload_image.php"
my code is as below for post:
-(IBAction) post:(id) sender
{
count = 0;
self.progress = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
self.progress.center = self.view.center;
progress.hidden = NO;
[self.view addSubview:self.progress];
nmyTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(updateUI:) userInfo:nil repeats:YES];
NSString *filename = [NSString alloc];
filename = [self randomStringWithLength:5];
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 100);
NSError *error;
NSData *searchData;
NSHTTPURLResponse *response;
// setting up the URL to post to
NSString *urlString = #"http://dev9.edisbest.com/upload_image.php";
// setting up the request object now
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
You might want to generate a random boundary.. this is just the same
as my output from wireshark on a valid html post
*/
NSString *boundary = [NSString stringWithString:#"---------------------------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];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#.jpg\"\r\n",filename] 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 stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
searchData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"%#",response);
NSString *imageName;
imageName = [[NSString alloc] initWithData:searchData encoding:NSUTF8StringEncoding];
NSLog(#"retrun Result of Upload Photo.. %#",imageName);
[request setHTTPBody:body];
// now lets make the connection to the web
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{ NSLog(#"Finished with status code: %i", [(NSHTTPURLResponse *)response statusCode]); }];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
///self.returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#",returnString);
}
when i build and run i will be asked to choose image and when i select an image to upload
I got a message as the following
**[Switching to process 553 thread 0x4e03]
2015-04-28 12:08:12.856 image-video-upload[553:207] (null)
2015-04-28 12:08:12.857 image-video-upload[553:207] retrun Result of Upload Photo..
2015-04-28 12:08:12.889 image-video-upload[553:207] Finished with status code: 0**
Above message shown in my console and crashed
Try this..
UIImage *image=[UIImage imageNamed:#"i3.png"];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSString *encodedString = [imageData base64EncodedStringWithOptions:0];
NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
[dictionnary setObject:encodedString forKey:#"imageData"];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary
options:kNilOptions
error:&error];
NSString *urlString = #"http://Your url";
NSURL *url = [NSURL URLWithString:urlString];
// Prepare the request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"json" forHTTPHeaderField:#"Data-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:jsonData];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&theResponse
error:&errorReturned];
Here is the code from my project to upload image
// 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=%#", BoundaryConstant];
[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", BoundaryConstant] 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", BoundaryConstant] 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", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// set URL
[request setURL:requestURL];

Migrating from NSURLConnection to NSURLSession

I am trying to migrate to NSURLSession so I can send multiple images to my server and stop when I get the needed response. But my completion block never gets called. Would appreciate if you could tell me if I am doing the migration correctly.
Here is my old code that works fine-
-(void) sendImgWithText:(UIImage*)img
{
NSURL *requestURL = [NSURL URLWithString:#"Some URL"];
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"*****";
NSString *lineEnd = #"\r\n";
NSString *twoHyphens = #"--";
// 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)
// UIImage *imgColor = [UIImage imageNamed:#"9.jpg"];
UIImage * imageToPost = [[UIImage alloc] init];
UIImageWriteToSavedPhotosAlbum(imageToPost, nil, nil, nil);
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"%#%#%#", twoHyphens,boundary, lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test.jpg\"%#",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
// [body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"%#",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"%#%#%#%#", twoHyphens,boundary, twoHyphens,lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
NSLog(#"%#",requestURL);
NSLog(#"%f,%f",imageToPost.size.height,imageToPost.size.height);
// set URL
[request setURL:requestURL];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
And here is the version(I got most of it from other stack overflow articles)
- (void) serverRequestWithImage:(UIImage *)img completion:(void (^)(id responseObject, NSError *error))completion
{
NSURL *requestURL = [NSURL URLWithString:#"Some URL"];
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"*****";
NSString *lineEnd = #"\r\n";
NSString *twoHyphens = #"--";
// 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];
UIImage * imageToPost = [[UIImage alloc] init];
imageToPost = img;
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"%#%#%#", twoHyphens,boundary, lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test.jpg\"%#",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
// [body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"%#",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"%#%#%#%#", twoHyphens,boundary, twoHyphens,lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
NSLog(#"%#",requestURL);
NSLog(#"%f,%f",imageToPost.size.height,imageToPost.size.height);
// set URL
[request setURL:requestURL];
NSURLSessionTask *task =
[session
dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
// report any network-related errors
NSLog(#"Got Response 1");
if (!data) {
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil, error);
});
}
return;
}
// report any errors parsing the JSON
NSError *parseError = nil;
_responseData = [NSMutableData dataWithData:data];
if (_responseData) {
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil, parseError);
});
}
return;
}
// if everything is ok, then just return the JSON object
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(_returnedData, nil);
});
}
}];
[task resume];
}
And here is my call method from the other class
- (IBAction)GetData:(id)sender
{
[_imageView setImage:[UIImage imageNamed:#"9.jpg"]];
msg = [[Message alloc] init];
[msg initData];
msg.delegate=self;
[msg serverRequestWithImage:_imageView.image completion:^(id responseObject, NSError *error)
{
if (responseObject) {
// do what you want with the response object here
NSLog(#"Got Data");
} else {
NSLog(#"%s: serverRequest error: %#", __FUNCTION__, error);
}
}];
}
Items:
I didn't see the initialization of NSURLSession. That's something you should show in your question. You could also check in your "send image" method that session is non-nil.
It looks like you are starting with a file (#"9.jpg"). If so, -[NSURLSession uploadTaskWithRequest:fromFile:completionHandler:] might save you a bunch of trouble.
Unrequested advice, with all that entails: :)
In my view, -serverRequestWithImage:completion: is a poor name for that method. It implies that it returns a request object, and does not tell you that it actually sends the request. Something active, like -uploadImage:completionHandler: might be better.
Idiomatically, all method names should start lowercase, i.e. -getData:.

Resources