I send an image to a server HTTP with this code:
-(NSDictionary*)sendImage:(UIImage*)image withDescription:(NSString*)description andTarget:(NSString*)target andTargetId:(int)targetId {
__block NSDictionary *result = nil;
NSData *imageData = UIImagePNGRepresentation(image);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#", PREFIX_URL_REQUEST, SEND_IMAGE]]];
[request setHTTPMethod:REQUEST_TYPE_POST];
NSString *boundary = [[NSString alloc] init];
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=\"file\"; filename=\"%#.%d\"rn", target, targetId] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type: application/%#.png\r\n\r\n", [NSString stringWithFormat:#"%#_%d", target, targetId]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#", result.description);
dispatch_semaphore_signal(sem);
}];
[dataTask resume];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
return result;
}
this is the server code:
session_start();
if ( isset($_SESSION['username']) ) {
$params = explode(".", basename($_FILES["file"]["name"]));
$target = array_values($params)[0];
$id = array_values($params)[1];
if ( ($target == "profile") || ($target == "question" && $_SESSION["waitingImagesQuestion"] > 0) || ($target == "answer" && $_SESSION["waitingImagesAnswer"] > 0) ) {
$imageDirectory = "images/".round(microtime(true)*1000).".png";
if ( move_uploaded_file($_FILES["file"]["tmp_name"], $imageDirectory) ) {
switch ( $target ) {
case "profile":
print JsonBuilder::putRecordProfileImage($imageDirectory);
return;
case "answer":
$_SESSION["waitingImagesAnswer"] --;
print JsonBuilder::putRecordAnswerImage($imageDirectory, $id);
return;
case "question":
$_SESSION["waitingImagesQuestion"] --;
print JsonBuilder::putRecordQuestionImage($imageDirectory, $id);
return;
}
}
}
}
print JsonBuilder::getStringError();
works, but only when I call the client method so ([UIImage imageNamed:#"aaa.png"]):
[sender sendImage:[UIImage imageNamed:#"aaa.png"] withDescription:#"" andTarget:#"profile" andTargetId:1];
if I call the method with an UIImage (for example a photo taken from the camera roll), so:
-(void)sendImage:(UIImage*)image {
return [sender sendImage:image withDescription:#"" andTarget:#"profile" andTargetId:1];
}
doesn't work!
Why?
Thanks
now it works:
-(NSDictionary*)sendImage:(UIImage*)image withDescription:(NSString*)description andTarget:(NSString*)target andTargetId:(int)targetId {
if ( image != nil ) {
NSData *imageData = UIImageJPEGRepresentation(image, 0.33f);
__block NSDictionary *result = nil;
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#", PREFIX_URL_REQUEST, SEND_IMAGE]]];
[request setHTTPMethod:REQUEST_TYPE_POST];
NSString *boundary = #"0xKhTmLbOuNdArY";
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=\"file\"; filename=\"%#.%d\"rn", target, targetId] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type: application/%#.png\r\n\r\n", [NSString stringWithFormat:#"%#_%d", target, targetId]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
dispatch_semaphore_signal(sem);
}];
[dataTask resume];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
return result;
}
return nil;
}
Related
I use the following code to upload images to the server:
void call_MediaUploadAPI(NSArray *parameters, NSString *url, BOOL isAnUpdate, SuccessBlock successBlock, FailureBlock failureBlock)
{
NSString *boundary = #"----WebKitFormBoundary7MA4YWxkTrZu0gW";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#", BASEURL, url]]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:600.0];
[request setHTTPMethod:#"POST"];
NSString *token = [[NSUserDefaults standardUserDefaults]valueForKey:TOKEN];
NSString *authValue = [NSString stringWithFormat: #"JWT %#",token];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
NSError *error;
NSMutableData *body = [NSMutableData data];
for (NSDictionary *param in parameters) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
if (param[#"fileName"]) {
NSString *mimetype = [[NetworkIntractor sharedManager] mimeTypeForPath:param[#"fileName"]];
NSData *imageData = [NSData dataWithContentsOfFile:param[#"fileName"]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition:form-data; name=\"%#\"; filename=\"%#\"\r\n", param[#"name"], param[#"fileName"]]dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type: %#\r\n\r\n", mimetype]dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
if (error) {
NSLog(#"%#", error);
}
} else {
[body appendData:[[NSString stringWithFormat:#"Content-Disposition:form-data; name=\"%#\"\r\n\r\n", param[#"name"]]dataUsingEncoding:NSUTF8StringEncoding]];
if ([param[#"name"] isEqualToString:#"data"]) {
[body appendData:[NSJSONSerialization dataWithJSONObject:param[#"value"] options:0 error:nil] ];
}else{
[body appendData:[[NSString stringWithFormat:#"%#", param[#"value"]]dataUsingEncoding:NSUTF8StringEncoding] ];
}
}
}
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary]dataUsingEncoding:NSUTF8StringEncoding] ];
[request setHTTPBody:body];
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error == nil) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
if (dict != nil) {
NSLog(#"multipart api response : %#", dict);
successBlock(dict,response);
}else
{
NSLog(#"multipart api failure response : %#", error);
failureBlock(error,response);
}
}}];
[task resume];
}
I tried giving different combination of timeout intervals like this:
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.timeoutIntervalForRequest = 150.0f;
config.timeoutIntervalForResource = 300.0f;
self.session = [NSURLSession sessionWithConfiguration:config delegate:nil delegateQueue:nil];
But, for a bit larger image files, I never get response back from the server though the image gets uploaded as I can find them available in the admin panel.
Send data to server works in postman but getting error in Objective-C.
I tried to achieve this one failed from server. I referred below links does not work. Getting error upload failed. What am I doing wrong?
Upload image to server ios
how to POST value while uploading image in iOS objective c
My Code:
NSData *dataImage = UIImageJPEGRepresentation(myImage, 1.0f);
// set your URL Where to Upload Image
NSString *urlString = #"http://xxxxxxxxxxxxxxxx/index.php/API/uploadClaim";
NSDictionary *user = [[NSUserDefaults standardUserDefaults] objectForKey:#"userDetails"];
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:#"filename" forKey:#"file_name"];
[_params setObject:#"photo" forKey:#"file_type"];
[_params setObject:[[user objectForKey:#"user_data"] objectForKey:#"id"] forKey:#"user_id"];
NSString *BoundaryConstant = #"----------V2ymHFg03ehbqgZCaKO6jy";
NSString* FileParamConstant = #"image";
NSURL* requestURL = [NSURL URLWithString:urlString];
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:120];
[request setHTTPMethod:#"POST"];
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
if (dataImage) {
[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:dataImage];
[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:#"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// set URL
[request setURL:requestURL];
NSURLResponse *response = nil;
NSError *requestError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&requestError];
Here is my working code to upload one or multiple image files:
Please note: you should pass images/files data in an NSDictionary with proper key values & You should set key name as your server expecting in upload call.
For example in your case it is file
parameters dictionary will be your other parameters to send with file
- (void) performNetworkEventRequestCallWithFileUpload :(NSMutableDictionary*) imagesData : (NSMutableDictionary*)parameters completionBlock:(void (^)(BOOL succeeded, NSDictionary *dict))completionBlock {
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] init];
[urlRequest setURL:[NSURL URLWithString:BASE_URL]];
[urlRequest setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[urlRequest addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[parameters enumerateKeysAndObjectsUsingBlock: ^(NSString *key, NSString *object, BOOL *stop) {
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n",key] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",object] dataUsingEncoding:NSUTF8StringEncoding]];
}];
[imagesData enumerateKeysAndObjectsUsingBlock: ^(NSString *key, NSData *object, BOOL *stop) {
if ([object isKindOfClass:[NSData class]]) {
if (object.length > 0) {
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *timeSTamp = [NSString stringWithFormat:#"%#",[NSDate date]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"%#.jpg\"\r\n",key,timeSTamp] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:object]];
}
}
}];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[urlRequest setHTTPBody:body];
AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = nil;
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:urlRequest completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
completionBlock (NO, responseObject);
} else {
NSLog(#"success");
completionBlock (YES, responseObject);
}
}];
[dataTask resume];
}
Here i am using Afnetworking for Uplaoding image us Multipart format, its working fine. So, check it. If its ok for you just vote my answer.
#import "AFHTTPSessionManager.h"
{
NSData * profileData;
}
profileData = UIImageJPEGRepresentation(chosenImage, 1.0);
-(void)UploadImageApi
{
NSString *URLString = #“YourURL”;
/*Profile data is nothing your pick image from gallery or Camera, That saving in profile data.*/
NSMutableDictionary *parameter=[[NSMutableDictionary alloc]init];
[parameter setObject:#“yourObj” forKey:#“YourKey”];
[parameter setObject:#“yourObj” forKey:#“YourKey”];
[parameter setObject:#“yourObj” forKey:#“YourKey”];
if(profileData==nil)
{
[parameter setObject:#"" forKey:#“YourKey”];
}
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
manager.responseSerializer = [AFJSONResponseSerializer
serializerWithReadingOptions:NSJSONReadingAllowFragments];
[manager POST:URLString parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
if(profileData!=nil)
{
[formData appendPartWithFileData:profileData name:#“YourKeyName” fileName:#"filename.jpg" mimeType:#"image/jpeg"];
}
}
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"%#",responseObject);
NSMutableArray *json = [responseObject mutableCopy];
NSLog(#" success = %#",json);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"%#",error);
}];
}
you can use much simpler approach for data as well as for image:
NSDictionary *headers = #{ #"content-type": #"multipart/form-data; boundary=---------------------------14737809831466499882746641449",
#"cache-control": #"no-cache" };
NSMutableArray *parameters = [[NSMutableArray alloc]initWithObjects:#"param1",#"param2", nil];
NSMutableArray *values = [[NSMutableArray alloc]initWithObjects:#"value1",#"value2", nil];
NSString *boundary = #"---------------------------14737809831466499882746641449";
//NSData *dataImage = UIImageJPEGRepresentation(imageView.image, 1.0f); uncomment for image
NSMutableData *body = [NSMutableData data];
for (int i=0;i<parameters.count;i++) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n",[parameters objectAtIndex:i]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",[values objectAtIndex:i]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}
NSLog(#"Parameters : %#",parameters);
NSLog(#"Values : %#",values);
//image
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"image\"; filename=\"file.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[NSData dataWithData:dataImage]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://your API URL here"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:body];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"%#", error);
} else {
NSMutableArray *array=[[NSMutableArray alloc]init];
rowBtnTableLast2=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
NSLog(#"PostMethod Result : %#, PostMethod Error : %#",array,error);
}}];
[dataTask resume];
I want to upload an image from a dictionary which looks like this,
{
pic_image : file attache
pic_user_id : 1
pic_name : abcd.jpg
}
where file attached is the image i want to upload from the image view, How to achieve this?
this my function to upload image that is inside a dictionary
-(void)uploadImageWithparams:(NSDictionary *)params withDelegate:(id)delegateObject withHandler:(HMResponseBlock)block{
// This isn't actually my url btw
// setting up the request object now
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#,%#",kBaseUrl,#"page=user"]]];
[request setHTTPMethod:#"POST"];
NSMutableArray *parameters = [[NSMutableArray alloc] init];
for (NSString *key in params.allKeys) {
if([key rangeOfString:#"pic_image"].location != NSNotFound){
[parameters addObject:#{#"fileName": key, #"value": params[key]}];
}else {
[parameters addObject:#{#"name": key, #"value": params[key]}];
}
}
NSLog(#"The parameters are %#",parameters);
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSError *error;
NSMutableData *body = [NSMutableData data];
for (NSDictionary *param in parameters) {
if (param[#"fileName"]) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"photo\"; filename=\"%#\"\r\n", #"abcd"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:param[#"value"]];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}else {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition:form-data; name=\"%#\"\r\n\r\n", param[#"name"]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", param[#"value"]] dataUsingEncoding:NSUTF8StringEncoding]];
}
}
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"%#", error);
} else {
NSDictionary *json = nil;
NSError *err;
if(data){
json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&err];
}
block(json,err);
}
}];
[dataTask resume];
}
Get image name from dictionary by key name
ex:
NSString *imageName = myDictioanry[#"pic_name"];
by this code you can get image name from dictionary
UIImage *image = [UIImage imageNamed:imageName];
you can get image from image name by above code
or else you can get image from imageView and convert to NSData by below code
UIImage *image = myImageView.image;
if you want code for upload image to server, click this link
imageUploadLink
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:.
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!";
}
?>