I am trying to send a post request.
Here is my try:
-(void)Test{
NSDictionary * orderMasterDict = #{#"distributorId":#10000,
#"fieldUsersId": #3,
#"itemId":#0,#"orderMatserId":#56358 };
Globals.OrderDetailsArray = [NSMutableArray arrayWithObjects:orderDetailsDictAnatomy,orderDetailsDictTexture,orderDetailsDictTranslucency, nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:Globals.OrderDetailsArray options:NSJSONWritingPrettyPrinted error:nil];
NSData *postData2 = [NSJSONSerialization dataWithJSONObject:orderMasterDict options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString2 = [[NSString alloc] initWithData:postData2 encoding:NSUTF8StringEncoding];
NSString *jsonString = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:jsonString2 forKey:#"orderMaster"];
[_params setObject:jsonString forKey:#"orderDetails"];
[_params setObject:[NSString stringWithFormat:#"3"] forKey:#"userId"];
[_params setObject:[NSString stringWithFormat:#"ALRAISLABS"] forKey:#"subsCode"];
// 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 = #"imageUpload";
// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:#"http://192.168.0.102:8080/Demo/Test/create"];
// 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(_uploadImageView.image, 0.6);
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];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// set URL
[request setURL:requestURL];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error){
NSLog(#"ERROR :",error);
}else{
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(#"response status code: %ld", (long)[httpResponse statusCode]);
if ([httpResponse statusCode] == 200) {
NSLog(#"StatusCode : %ld",(long)[httpResponse statusCode]);
}else{
NSLog(#"Error");
}
}
}] resume];}
How to make a multipartFormData request?
I tried googling for it, couldn't find any answer suitable for this situation, and thought well .Please help me finding the right solution.
Thanks in advance.
First you change your image in NSData then help of AFNetworking you can post your image.
NSData *data = UIImagePNGRepresentation(yourImage);
imageData = [data base64EncodedStringWithOptions: NSDataBase64Encoding64CharacterLineLength];
Then use this code:
NSMutableDictionary *finaldictionary = [[NSMutableDictionary alloc] init];
[finaldictionary setObject:imageData forKey:#"image"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST: [NSString stringWithFormat: #"%#%#", IQAPIClientBaseURL, kIQAPIImageUpload] parameters: finaldictionary constructingBodyWithBlock: ^(id<AFMultipartFormData> formData) { }
progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"Success response=%#", responseObject);
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData: responseObject options: NSJSONReadingAllowFragments error: nil];
NSLog(#"%#", responseDict);
}
failure: ^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"Errorrrrrrr=%#", error.localizedDescription);
}
];
By using Alamofire
-(void)CreateOrder{
NSString * urlString = [NSString stringWithFormat:#"YOUR URL"
NSDictionary * orderMasterDict = #{#"distributorId":stakeholderID,
#"fieldUsersId": userID,
#"itemId":#0,#"orderMatserId":#0 };
Globals.OrderDetailsArray = [NSMutableArray arrayWithObjects:orderDetailsDictAnatomy,orderDetailsDictTexture,orderDetailsDictTranslucency, nil];
NSDictionary * consumerDetails = #{#"consumerName":Globals.PatientName,#"consumerReferenceId":Globals.PatientID,#"notes":Globals.PatientNotes,#"cunsumerContacNumber":#"456464654654"};
NSData *postData = [NSJSONSerialization dataWithJSONObject:Globals.OrderDetailsArray options:NSJSONWritingPrettyPrinted error:nil];
NSData *postData2 = [NSJSONSerialization dataWithJSONObject:orderMasterDict options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString2 = [[NSString alloc] initWithData:postData2 encoding:NSUTF8StringEncoding];
NSString *jsonString = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
//retrieving userId from UserDefaults
prefs = [NSUserDefaults standardUserDefaults];
NSString * userIdString = [prefs stringForKey:#"userID"];
NSDictionary *parameters = #{#"orderMaster": jsonString2, #"orderDetails" : jsonString ,#"userId" : userIdString,#"subsCode" : #"ABC_MDENT"};
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//For adding Multiple images From selected Images array
int i = 0;
for(UIImage *eachImage in selectedImages)
{
UIImage *image = [self scaleImage:eachImage toSize:CGSizeMake(480.0,480.0)];
NSData *imageData = UIImageJPEGRepresentation(image,0.3);
[formData appendPartWithFileData:imageData name:#"imageUpload" fileName:[NSString stringWithFormat:#"file%d.jpg",i ] mimeType:#"image/jpeg"];
i++;
}
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
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) {
NSLog(#"responseObject : %#",responseObject);
if (error) {
NSlog(#"error")
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if ([httpResponse statusCode] == 200) {
resposeStatusCode = [responseObject objectForKey:#"statusCode"];
}else{
NSLog(#"requestError");
}
}
}];
[uploadTask resume]; }
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.
I am using below code to send image from gallery to amazon server in ios but it is not successful. May i know the format in which it need to send and do i need to pass just the file name or the entire path of the image?
Thanks.
NSDictionary *headers = #{ #"content-type": #"multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
#"x-access-token": #"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2UxOTAiLCJpc3MiOiJodHRwczovL3d3dy5oY3VlLmNvIiwicGVybWlzc2lvbnMiOiJhdXRoZW50aWNhdGVkIiwidXNlcmlkIjpudWxsLCJpYXQiOjE0ODYyMDczNDB9.ewu2QtoHl1kBSrM1y6yL9Jr58kiGmhCsy2YWoFrE2OU",
#"cache-control": #"no-cache",
};
NSArray *parameters = #[ #{ #"name": #"username", #"fileName": localFilePath} ];
NSString *boundary = #"----WebKitFormBoundary7MA4YWxkTrZu0gW";
NSError *error;
NSMutableString *body = [NSMutableString string];
for (NSDictionary *param in parameters) {
[body appendFormat:#"--%#\r\n", boundary];
if (param[#"fileName"]) {
[body appendFormat:#"Content-Disposition:form-data; name=\"%#\"; filename=\"%#\"\r\n", param[#"name"], param[#"fileName"]];
[body appendFormat:#"Content-Type: %#\r\n\r\n", param[#"contentType"]];
[body appendFormat:#"%#", [NSString stringWithContentsOfFile:param[#"fileName"] encoding:NSUTF8StringEncoding error:&error]];
if (error) {
NSLog(#"%#", error);
}
} else {
[body appendFormat:#"Content-Disposition:form-data; name=\"%#\"\r\n\r\n", param[#"name"]];
[body appendFormat:#"%#", param[#"value"]];
}
}
[body appendFormat:#"\r\n--%#--\r\n", boundary];
NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://zambalauploaddev.ap-southeast-1.elasticbeanstalk.com/upload"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"%#", error);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(#"%#", httpResponse);
NSDictionary * responseDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"Reponse Dict:%#",responseDict);
}
}];
[dataTask resume];
I'm Trying to upload image to server with headers Hope my code is fine but i don't know it cannot upload. My code is
{
NSDictionary *headers = #{ #"content-type":#"multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
#"p-auth-token":self.token};
NSString *urlString = [ NSString stringWithFormat:#"http://ica.com/facilitator/server/v1/media"];
UIImage *image= profile_Image;
NSData *imageData = UIImageJPEGRepresentation(image, 0.1);
double my_time = [[NSDate date] timeIntervalSince1970];
NSString *imageName = [NSString stringWithFormat:#"%d",(int)(my_time)];
NSString *string = [NSString stringWithFormat:#"%#%#%#", #"Content-Disposition: form-data; name=\"file\"; filename=\"", imageName, #".jpg\"\r\n\""];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setAllHTTPHeaderFields:headers];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:string] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *statusDict = [[NSDictionary alloc]init];
statusDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
[SVProgressHUD dismiss];
NSLog(#"Images form server %#", statusDict);
}] resume];
}
Try AFNetworking with below code,
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:#"upload_url" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:data name:#"upload_file_name" fileName:#"somefilename.jpg" mimeType:#"mime_type_of_file"] // you file to upload
} 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];
I tried to upload multiple images to server, I picked the images by using QBImagePickerController and upload to server. But i'm not getting the proper image while retrieve image from server.how to upload PHAsset image to server.
{- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets {
self.imagesKeysArray = [NSMutableArray new];
for (PHAsset *asset in assets) {
// Do something with the asset
NSDictionary *headers = #{ #"content-type": #"multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
#"p-auth-token": #"afc1577772eb73c910a4e180290f" };
NSArray *resources = [PHAssetResource assetResourcesForAsset:asset];
NSString *orgFilename = ((PHAssetResource*)resources[0]).originalFilename;
NSArray *parameters = #[ #{ #"name": #"file[]", #"fileName": orgFilename } ];
NSString *boundary = #"----WebKitFormBoundary7MA4YWxkTrZu0gW";
NSError *error;
NSMutableString *body = [NSMutableString string];
for (NSDictionary *param in parameters) {
[body appendFormat:#"--%#\r\n", boundary];
if (param[#"fileName"]) {
[body appendFormat:#"Content-Disposition:form-data; name=\"%#\"; filename=\"%#\"\r\n", param[#"name"], param[#"fileName"]];
[body appendFormat:#"Content-Type: %#\r\n\r\n", param[#"contentType"]];
[body appendFormat:#"%#", [NSString stringWithContentsOfFile:param[#"fileName"] encoding:NSUTF8StringEncoding error:&error]];
if (error) {
NSLog(#"%#", error);
}
} else {
[body appendFormat:#"Content-Disposition:form-data; name=\"%#\"\r\n\r\n", param[#"name"]];
[body appendFormat:#"%#", param[#"value"]];
}
}
[body appendFormat:#"\r\n--%#--\r\n", boundary];
NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://frica.com/facilitator/server/v1/media"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"%#", error);
} else {
NSDictionary *serverDatadict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSString *keys = [[[[serverDatadict valueForKey:#"result"]objectForKey:#"file1"]objectForKey:#"result"]valueForKey:#"key"];
[self.imagesKeysArray addObject:keys];
NSLog(#"Pic keys %#", self.imagesKeysArray);
}
}];
[dataTask resume];
}
[self dismissViewControllerAnimated:YES completion:NULL];
}
}
I desperately need to show a progress bar or an activity indicator , because image uploading takes time. Below is my code, I cannot figure it out why progress bar is not showing. I have used ProgressHUD.
[ProgressHUD show:#"Please wait..."];
NSDictionary *params =#{ #"name":self->Name.text, #"contact_no":self->ContactNo.text,#"email_id":self->EmailId.text,#"s_date":Date,#"s_time":Time,#"streat":Street,#"city":City,#"state":State};
NSData *uploadData = Data;
NSString *urlString = [NSString stringWithFormat:#"http://fsttest.com/iosservice/supremo/add_supremo"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSString *kNewLine = #"\r\n";
NSMutableData *body = [NSMutableData data];
for (NSString *name in params.allKeys) {
NSData *values = [[NSString stringWithFormat:#"%#", params[name]] dataUsingEncoding:NSUTF8StringEncoding];
[body appendData:[[NSString stringWithFormat:#"--%#%#", boundary, kNewLine] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"", name] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#%#", kNewLine, kNewLine] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:values];
[body appendData:[kNewLine dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"file_name\"; filename=\"test\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:uploadData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
choice 1
as your way continution add the delegate and check like
- (void)connection:(NSURLConnection *)connection
didSendBodyData:(NSInteger)bytesWritten
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
float progress = [[NSNumber numberWithInteger:totalBytesWritten] floatValue];
float total = [[NSNumber numberWithInteger: totalBytesExpectedToWrite] floatValue];
NSLog(#"progress/total %f",progress/total);
}
choice 2
modify your request from sendSynchronousRequest to sendAsynchronousRequest for e,g
// NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
call the method like
// set URL
[request setURL:[NSURL URLWithString:baseUrl]];
// add your progress bar here
[ProgressHUD show:#"Please wait..."];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
[ProgressHUD dismiss];
if ([httpResponse statusCode] == 200) {
NSLog(#"success");
if ([data length] > 0 && error == nil)
[delegate receivedData:data];
// hide the progress bar here
}
}];
You can use AFNetworking for easily upload image. here click on AFNeworking Download. Same as your code upload images.
-(void)imageUpload
{
#try
{
[self progressViewDispaly];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager.requestSerializer setTimeoutInterval:600.0];
[manager POST:YOUR_WEB_SERVICE_NAME parameters:YOUR_REQUEST_PARA constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData)
{
for(NSString *strImageName in ImageArray) //if multiple images use image upload
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:strImageName];
if (path != nil)
{
NSData *imageData = [NSData dataWithContentsOfFile:path];
[formData appendPartWithFileData:imageData name:[NSString stringWithFormat:#"job_files[]"] fileName:[NSString stringWithFormat:#"%#",[[strImageName componentsSeparatedByString:#"/"] lastObject]] mimeType:#"image/jpeg"];
}
else
{
}
}
} progress:^(NSProgress * _Nonnull uploadProgress)
{
[self performSelectorInBackground:#selector(makeAnimation:) withObject:[NSString stringWithFormat:#"%f",uploadProgress.fractionCompleted]];
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
[SVProgressHUD dismiss];
[_progressView removeFromSuperview];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
} #catch (NSException *exception)
{
NSLog(#"%#",exception.description);
}
}
-(void)makeAnimation:(NSString *)str
{
float uploadProgress = [str floatValue];
[_progressView setProgress:uploadProgress];
}
-(void)progressViewDispaly
{
UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:#"statusBarWindow"] valueForKey:#"statusBar"];
_progressView = [[UIProgressView alloc] init];//WithProgressViewStyle:UIProgressViewStyleBar];
_progressView.frame = CGRectMake(0, 0, CGRectGetWidth(statusBar.frame),20);
_progressView.backgroundColor = [UIColor blueColor];
_progressView.progressTintColor = [UIColor whiteColor];
[statusBar addSubview:_progressView];
}