Currently, I've trying to write a method in Objective C that takes in a UIImage and a NSString and makes a POST request to a server. Unfortunately, I have trouble getting it to send anything. When I tried the form with an HTML form, I was able to successfully upload a photo and the parameters. However, I am unable to replicate it in my iOS app. I keep getting a 404 error when I try to make a POST request.
I've tried two different methods of sending a multiform data POST request according to its Github page to no success. I've debugged the UIImage in Xcode and I see that it actually exists. I'm thinking it has something to do with the parameters I'm sending. Should the parameters be part of formDataAppend or just as a dictionary as I did below?
The commented part corresponds with the tutorial on its Github. The uncommented section contains parts from browsing Stackoverflow still to no avail.
+(void) uploadPhotoWithID:(NSString *)ownerID andPhotoImage:(UIImage *)image andCompletionHandler:(void (^)(MZPhoto *, NSError *))callback{
NSData *imageData = UIImageJPEGRepresentation(image, 1);
NSDictionary *parameters = #{#"owner_id": ownerID};
// NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:upload_photo_url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
// [formData appendPartWithFileData:imageData name:#"photo" fileName:#"temp.jpg" mimeType:#"image/jpeg"];
// } error:nil];
// AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//
// NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
// if(error){
// NSLog(#"File Upload Failed");
//
// }
// else{
// NSLog(#" %#", responseObject);
// MZPhoto *photo = [[MZPhoto alloc] initWithDictionary:responseObject error:nil];
// callback(photo, nil);
// }
// }];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:upload_photo_url]];
[manager POST:upload_photo_url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFileData:imageData name:#"photo" fileName:#"photo.jpg" mimeType:#"image/jpeg"];
} progress:nil
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#" %#", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#" Failed");
}];
}
Here is my Node.JS function,
exports.upload_photo = function(req, res, next) {
var owner_id = req.body.owner_id;
console.log(owner_id);
pg.connect(connectionString, function(err, client, done) {
if (err) {
done();
console.log(err);
return res.status(500).json({success: false, data: err});
}
var query = client.query("INSERT INTO photos (likes, dislikes, user_id) " +
"VALUES (0, 0, $1) RETURNING photo_id, likes, dislikes, user_id", [owner_id]);
var result;
console.log(req.file);
query.on('row', function(row) {
row.file_url = baseFileURL + row.photo_id + '.jpg';
result = row;
});
query.on('end', function() {
done();
fs.rename('./static/photos/' + req.file.filename, './static/photos/' + result.photo_id + '.jpg', function(err) {
if(err) console.log("Error Renaming the file!");
return res.json(result);
});
});
});
console.log("Received photo upload from: " + owner_id);
}
Try with following function
- (void) postServerRequest:(NSDictionary *)paramDict withData:(NSData*)fileData andType:(uploadType)uploadType Callback:(ResponseBlock) block{
NSString * strServiceURL = #"Your Webservice URL";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager.requestSerializer setValue:#"multipart/form-data" forHTTPHeaderField:#"Content-Type"];
[manager POST:strServiceURL parameters:paramDict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if (fileData!=nil){
[formData appendPartWithFileData:fileData name:#"Key name on which you will upload file" fileName:#"Image name" mimeType:#"image/jpeg"];
}
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
DLOG(#"Success: %#", responseObject);
block(responseObject,nil);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DLOG(#"Error: %#", error);
block (nil , error);
}];
}
Related
I am trying to upload a picture on server with Multiparts using AFNetworking. I have tried to make a simple POST request without Image and it works fine. Now, can say that service URL is absolutely fine and there is no issue with server and I can see that image URL that is saved in document directory is also fine and all the other parameters are fine too, because they all are working with simple request. Can anyone find some error in my code? My Code is:
(void)uploadPicture:(NSMutableDictionary *)param
{
NSString *string=[NSString stringWithFormat:#"%#%#",base_url,#"register"];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:string parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:getImagePath] name:#"picture" fileName:getImagePath mimeType:#"image/jpeg" error:nil];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setStringEncoding:NSUTF8StringEncoding];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"%# %#", response, responseObject);
NSDictionary *dict= [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
NSDictionary *dic=responseObject;
NSLog(#"");
}
}];
[uploadTask resume];
}
Try this function :
First Solution
Note : You need to customise as per your need
-(void)getResponeseWithURL:(NSString *)url WithParameter:(NSDictionary *)parameter WithImage:(UIImage *)image ImageArray:(NSMutableArray *)arrImage WithImageParameterName:(NSString *)imagename WithCallback:(void(^)(BOOL success, id responseObject))callback {
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:[NSString stringWithFormat:#"%#%#",BASEURL,url] parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if (image) {
[formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.8) name:imagename fileName:#"Image.jpg" mimeType:#"image/jpeg"];
}
else if (arrImage){
int i = 1;
for (UIImage *recipeimage in arrImage) {
// this condition for maintain server side coloum format : ex name , name_2 , name_3
[formData appendPartWithFileData:UIImageJPEGRepresentation(recipeimage, 0.8) name:i == 1 ? imagename : [NSString stringWithFormat:#"%#_%d",imagename,i] fileName:#"Image.jpg" mimeType:#"image/jpeg"];
i++;
}
}
}error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
dispatch_async(dispatch_get_main_queue(), ^{
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
[UtilityClass showAlertWithMessage: #"Please try again" andWithTitle:#"Network Error" WithAlertStyle:AFAlertStyleFailure];
NSLog(#"Error: %#", [[NSString alloc]initWithData:[[error valueForKey:#"userInfo"] valueForKey:#"com.alamofire.serialization.response.error.data"] encoding:NSUTF8StringEncoding]);
[UtilityClass removeActivityIndicator];
callback(NO,nil);
} else {
callback(YES,responseObject);
}
}];
[uploadTask resume];
}
Second
May you have forgot to add ATS in your project plist file so you need to add this .
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
NSString *string=[NSString stringWithFormat:#"%#%#",base_url,#"register"];
#autoreleasepool {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager POST:strurl
parameters:parameters
constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
NSMutableArray *allKeys = [[imgParameters allKeys] mutableCopy];
for (NSString *key in allKeys) {
id object = [imgParameters objectForKey:key];
int timestamp = [[NSDate date] timeIntervalSince1970];
NSString *str = [[NSString alloc] initWithFormat:#"%d", timestamp];
NSString *ranstrin = [self randomStringWithLength:8];
// if ([key isEqualToString:#"image"]) {
str = [NSString stringWithFormat:#"TestThumb_%d_%#.jpg",
timestamp, ranstrin];
[formData appendPartWithFileData:object
name:key
fileName:str
mimeType:#"image/jpeg"];
}
}
progress:^(NSProgress *_Nonnull uploadProgress) {
}
success:^(NSURLSessionDataTask *_Nonnull task,
id _Nullable responseObject) {
complete(responseObject, nil);
}
failure:^(NSURLSessionDataTask *_Nullable task,
NSError *_Nonnull error) {
complete(nil, error);
}];
This is how I"m sending the request:
NSString *string = [NSString stringWithFormat:#"%#/API/Upload",BaseURLString];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
NSError *error;
manager.responseSerializer.acceptableContentTypes = nil;
for(NSData *eachImage in self.fetchedAtt) {
NSString *mystring = #"786";
NSURLRequest *request = [manager.requestSerializer multipartFormRequestWithMethod:#"POST" URLString:string parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFormData:eachImage name:#"myImage"];
[formData appendPartWithFormData:[mystring dataUsingEncoding:NSUTF8StringEncoding]
name:#"PracticeCode"];
} error:&error];
NSURLSessionDataTask *task = [manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(#"%#", error.localizedDescription);
return;
}
NSLog(#"%#", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
}];
[task resume];
}
}
Sometimes I get:
{ "Message": "Error writing MIME multipart body part to output
stream." }
//this is a 500 error
and sometimes I get
Request failed: unsupported media type (415)
You are trying to send multiple files in a single multiform request. Multipart doesn't work like this. You will have to make multiple multipart requests with 1 file at a time. So consider you have 20 files. You will create an async task that takes one file at a time, uploads it, and then performs the same function again for the next files.
And if you want to keep the references, you should return the file ids from the backend, and then append all the ids in a single array and send that array as a param in a separate api request to link the files with any object. Hope that makes sense.
Try this Afnetworking 3.0
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString: [NSString stringWithFormat:#"%#/API/Upload",BaseURLString]; parameters:#{#"text":#"name"} constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageurl]] name:#"bizcard" fileName:#"Businesscard.jpg" mimeType:#"image/jpeg"]; // you file to upload
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
dispatch_async(dispatch_get_main_queue(), ^{
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(#"Error: %#", [[NSString alloc]initWithData:[[error valueForKey:#"userInfo"] valueForKey:#"com.alamofire.serialization.response.error.data"] encoding:NSUTF8StringEncoding]);
callback(NO,nil);
[UtilityClass removeActivityIndicator];
} else {
callback(YES,responseObject);
}
}];
[uploadTask resume];
I am trying to upload data with AFNetworking and its successful. no problem with that but the problem is when I am doing it in background than the other requests blocks and doesn't give any response until upload progress finishes.
What I did is I made a singleton and declare AFURLSessionManager in that because I want all current running task.
+ (id)sharedInstance
{
static SharedManager *sharedMyManager = nil;
#synchronized(self) {
if (sharedMyManager == nil)
sharedMyManager = [[self alloc] init];
}
return sharedMyManager;
}
Let me tell you simple example.. for one controller, I made a request for upload process like below
ViewController1.m
-(void)postImage{
#try {
NSMutableDictionary *otherParameters = [[NSMutableDictionary alloc]initWithDictionary:_currentPlaceParameters];
[otherParameters setObject:[UtitlityManager getUserID] forKey:#"user_id"];
AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
NSMutableURLRequest *request =
[serializer multipartFormRequestWithMethod:#"POST" URLString:URL_UPLOAD_PHOTO_VIDEO parameters:otherParameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSData *thumbImageData = UIImageJPEGRepresentation(dataValue, 0.5);
[formData appendPartWithFileData:thumbImageData name:#"thumbnail" fileName:#"image.jpg" mimeType:#"image/jpeg"];
} error:nil];
//show progress bar on window
AFURLSessionManager *manager = [[SharedManager sharedInstance]manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
float uploadActualPercentage = uploadProgress.fractionCompleted * 100;
NSLog(#"Multipartdata upload in progress: %#",[NSString stringWithFormat:#"%f %%",uploadActualPercentage]);
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
} else {
NSDictionary *result=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
if([[result objectForKey:#"success"] integerValue]==1){
}else{
[Common showMessageWithMessage:#"Failed, Try again"];
}
}
}];
[uploadTask resume];
} #catch (NSException *exception) {
NSLog(#"EXC: %#",[exception description]);
}
}
And than I try to move another view controller and send a request for get other data ...
ViewController2.m
-(void)getData{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:url parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSDictionary* responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
} failure:^(NSURLSessionTask *operation, NSError *error) {
}];
}
But this doesn't give response until progress finishes... why so??
Even I try to set this upload process in dispatch_sync but it won't work ... any suggestion on this???
//webteam code for upload image
var hoardingjson = {
_id: id,
populationincomegroup: incomeGroupArray,
availablebydate: availDate,
title: title,
description: desc,
onemonthprice: oneMprice,
threemonthsprice: threeMprice,
sixmonthsprice: sixMprice,
oneyearprice: oneYrprice,
locality: locality,
streetname: streetName,
trafficdensity: trafficDensity,
populationcategory: populationDensity,
ownername: ownerName,
mobile: mobile,
leaseowner: currenrOwnerName,
length: hoardingWidth,
breadth: hoardingHeight,
latitude: lat,
longitude: lon,
registereddate: currentTimestamp,
createdate: "",
updatedate: "",
status: "",
ownerid: ownerid
};
var form_data = new FormData();
var imageCount = document.getElementById("editImages").files.length;
for (i = 0; i < imageCount; i++) {
form_data.append("file", document.getElementById("editImages").files[0]);
}
var xhr = new XMLHttpRequest();
xhr.open("POST", server_url + "UpdateHoarding", true);
xhr.setRequestHeader("hoardingjson", JSON.stringify(hoardingjson));
xhr.send(form_data);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
success = true;
$("#updateHoardingModal").modal("hide");
alert("Hoarding is updated successfully");
location.href = "home.jsp";
}
}
}
Ios code:
NSString * jsosSt=[self strOfthedata];
UIImage *imageOne = [UIImage imageNamed:#"edit.png"];
NSData *imageData1 = UIImageJPEGRepresentation(imageOne,0.6f);
NSString *fileName1 = [NSString stringWithFormat:#"%ld%c%c.jpeg", (long)[[NSDate date] timeIntervalSince1970], arc4random_uniform(26) + 'a', arc4random_uniform(26) + 'a'];
NSDictionary *params=#{#"token":appdeligate.userInf.tokenId,#"hoardingjson":[self strOfthedata]};
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:#"URL/CreateHoarding" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:savedImagePath] name:#"file" fileName:#"filename.jpg" mimeType:#"image/jpeg" error:nil];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableString *strParams = [[NSMutableString alloc]init];
for (NSString *key in [params allKeys]) {
[strParams appendFormat:#"%#=%#", key, params[key]];
[strParams appendString:#"&"];
}
[strParams deleteCharactersInRange:NSMakeRange([strParams length]-1, 1)];
[request setHTTPBody:[strParams dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
[progressView setProgress:uploadProgress.fractionCompleted];
NSLog(#"%f",uploadProgress.fractionCompleted);
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"%# %#", response, responseObject);
}
}];
[uploadTask resume];
Here it is using AFNetworking
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:stringURL]];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:stringURL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
//do not put image inside parameters dictionary as I did, but append it!
[formData appendPartWithFileData:nsdataFromBase64String name:#"" fileName:#"" mimeType:#"image/jpeg"];
}
success:^(NSURLSessionDataTask *task, id responseObject)
{
//here is place for code executed in success case
}
failure:^(NSURLSessionDataTask *task, NSError *error)
{
//here is place for code executed in error case
}];
stringURL is the URL where you want to upload/send the image.
NSData *nsdataFromBase64String = [[NSData alloc] initWithBase64EncodedString:pBytes options:0];
Where nsdataFromBase64String is image conversion to base64 string and decode the same on server
Check the mime type if you want png.
------------This is working for me---------------
-(void)UploadImagewithUrl:(NSString *)serviceURL
withJson:(NSString *)jsonStr
withtoken:(NSString *)Token_id
withImageArray:(NSArray *)imageURlArray
callback:(SuccessCallback)callback
failerCallback:(FailureCallback)failercallback {
NSString *baserl=[NSString stringWithFormat:#"%#?token=%#&hoardingjson=%#",serviceURL,Token_id,jsonStr];
baserl = [baserl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *lineEnd = #"\r\n";
NSString* twoHyphens = #"--";
NSString* boundary = #"*****";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:baserl parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
for (int i=0; i<imageURlArray.count; i++) {
NSData *imageData = [[NSFileManager defaultManager] contentsAtPath:[imageURlArray objectAtIndex:i]];
NSString *fileName = [NSString stringWithFormat:#"%ld%c.jpeg", (long)[[NSDate date] timeIntervalSince1970], arc4random_uniform(26) + 'a'];
[formData appendPartWithFormData:[twoHyphens dataUsingEncoding:NSUTF8StringEncoding] name:#"twoHyphens"];
[formData appendPartWithFormData:[boundary dataUsingEncoding:NSUTF8StringEncoding]
name:#"boundary"];
[formData appendPartWithFormData:[lineEnd dataUsingEncoding:NSUTF8StringEncoding]
name:#"lineEnd"];
[formData appendPartWithFileData:imageData
name:#"file"
fileName:fileName
mimeType:#"image/jpeg"];
}
[formData appendPartWithFormData:[lineEnd dataUsingEncoding:NSUTF8StringEncoding] name:#"lineEnd"];
[formData appendPartWithFormData:[twoHyphens dataUsingEncoding:NSUTF8StringEncoding] name:#"twoHyphens"];
[formData appendPartWithFormData:[boundary dataUsingEncoding:NSUTF8StringEncoding]
name:#"boundary"];
[formData appendPartWithFormData:[lineEnd dataUsingEncoding:NSUTF8StringEncoding]
name:#"lineEnd"];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
[SVProgressHUD showProgress:uploadProgress.fractionCompleted status:#"Uploading"];
if (uploadProgress.fractionCompleted==1)
{
[SVProgressHUD dismiss];
}
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
[progressView setProgress:uploadProgress.fractionCompleted];
NSLog(#"---response---- %#",uploadProgress);
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
failercallback([NSString stringWithFormat:#"%ld",error.code],#"failer");
NSLog(#"Error: %#", error);
} else {
callback(YES,responseObject);
NSLog(#"%# %#", response, responseObject);
}
}];
[uploadTask resume];
}
I studied with objective C programming . I don't know how to post image from the library to the api json (I took the picture from library use UIImagePickerController) . Thanks!
My json api:
http://i.stack.imgur.com/DLKZG.png
- (IBAction)btnAddBook:(id)sender {
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:#"http://192.168.1.54"]];
NSData *imageData = UIImageJPEGRepresentation(self.ivPickedImage.image, 1);
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setValue:self.tfTitle.text forKey:#"title"];
[params setValue:self.tfPrice.text forKey:#"price"];
[params setValue:self.tfProem.text forKey:#"proem"];
[params setValue:#"Vietnamese" forKey:#"language"];
AFHTTPRequestOperation *op = [manager POST:#"/api/books" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"file" fileName:#"photo.jpg" mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %# ***** %#", operation.responseString, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];
[op start];
Please use this below code:
NSDictionary *requestDictionary = [NSDictionary dictionaryWithObjectsAndKeys:abc.text, #"firstkey",xyz.text, #"secondkey" nil];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:#"YOUR API URL" parameters:requestDictionary constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{ [formData appendPartWithFileData:imageData name:#"profile_pic" fileName:#"photo.jpg" mimeType:#"image/jpeg"];
}
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSProgress *progress = nil;
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
NSLog(#"%#", response);
if (error) {
} else {
}
}];
[uploadTask resume];
Hope this helps.
By using AFNetworking multipart request. you can post image as data. here are the completed block of how to post image as multipart using AFNetworking
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:#"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:#"file://path/to/image.jpg"] name:#"file" fileName:#"filename.jpg" mimeType:#"image/jpeg" error:nil];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
[progressView setProgress:uploadProgress.fractionCompleted];
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"%# %#", response, responseObject);
}
}];
[uploadTask resume];
AFNetworking
Here your image is not passed as JSON. By using AFNetworking multipart request, all your request parameter passed as JSON and Image/Video that passed as NSData. where NSData is divided in multiple packets.
Thanks