iOS: Activity Indicator is not showing while calling post API - ios

here is my code I written for showing activityIndicator on the navigationBar.
In my project on every view, a loader is showing it is working fine either in the middle of the screen or else on network activityIndicator or loader on navigation.
But when I am trying to call below post method, activityIndicator is not showing (in this method only it is not working.)
I tried so many ways of writing programmatically and using storyboard.
Scenario 1 : Without entering reply content/message if click on submit button then activityIndicator will appear.
Scenario 2 : If I entered any reply content/message then activityIndicator will not show.
you can check this video: https://youtu.be/G_UZ_gLRlr8
#interface ViewController ()
{
UIActivityIndicatorView *activityIndicator;
}
#end
- (void)viewDidLoad {
[super viewDidLoad];
//adding activity indicator on the navigation bar
activityIndicator =
[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
activityIndicator.color=[UIColor blackColor];
UIBarButtonItem * barButton =
[[UIBarButtonItem alloc] initWithCustomView:activityIndicator];
// Set to Left or Right
[[self navigationItem] setRightBarButtonItem:barButton];
}
- (IBAction)submitButtonClicked:(id)sender {
[activityIndicator startAnimating];
if([_messageTextView.text isEqualToString:#""] || [_messageTextView.text length]==0)
{
[utils showAlertWithMessage:#"Enter the reply content.It can not be empty." sendViewController:self];
}else
{
[self replyTicketMethodCall];
}
}
-(void)replyTicketMethodCall
{
if ([[Reachability reachabilityForInternetConnection]currentReachabilityStatus]==NotReachable)
{
//connection unavailable
//[utils showAlertWithMessage:NO_INTERNET sendViewController:self];
[RKDropdownAlert title:APP_NAME message:NO_INTERNET backgroundColor:[UIColor hx_colorWithHexRGBAString:FAILURE_COLOR] textColor:[UIColor whiteColor]];
}else{
#try{
NSString *urlString=[NSString stringWithFormat:#"%#helpdesk/reply?token=%#",[userDefaults objectForKey:#"companyURL"],[userDefaults objectForKey:#"token"]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
// attachment parameter
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"media_attachment[]\"; filename=\"%#\"\r\n", file123] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type: %#\r\n\r\n", typeMime] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:attachNSData]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// reply content parameter
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"reply_content\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[_messageTextView.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
NSString * tickerId=[NSString stringWithFormat:#"%#",globalVariables.iD];
// ticket id parameter
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"ticket_id\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[tickerId dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// set request body
[request setHTTPBody:body];
NSLog(#"Request is : %#",request);
//return and test
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"ReturnString : %#", returnString);
NSError *error=nil;
NSDictionary *jsonData=[NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&error];
if (error) {
return;
}
NSLog(#"Dictionary is : %#",jsonData);
// "message": "Successfully replied"
if ([jsonData objectForKey:#"message"]){
NSString * msg=[jsonData objectForKey:#"message"];
if([msg isEqualToString:#"Successfully replied"])
{
[RKDropdownAlert title:NSLocalizedString(#"success", nil) message:NSLocalizedString(#"Posted your reply.", nil)backgroundColor:[UIColor hx_colorWithHexRGBAString:SUCCESS_COLOR] textColor:[UIColor whiteColor]];
[[NSNotificationCenter defaultCenter] postNotificationName:#"reload_data" object:self];
[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
}
else if ([jsonData objectForKey:#"message"])
{
NSString *str=[jsonData objectForKey:#"message"];
if([str isEqualToString:#"Token expired"])
{
MyWebservices *web=[[MyWebservices alloc]init];
[web refreshToken];
[self replyTicketMethodCall];
}
}
else
{
[self->utils showAlertWithMessage:#"Something went wrong. Please try again." sendViewController:self];
}
NSLog(#"Thread-Ticket-Reply-closed");
}
}#catch (NSException *exception)
{
[utils showAlertWithMessage:exception.name sendViewController:self];
NSLog( #"Name: %#", exception.name);
NSLog( #"Reason: %#", exception.reason );
return;
}
#finally
{
NSLog( #" I am in replytTicket method in TicketDetail ViewController" );
}
}
}
So this is the problem I am facing.
What is going wrong? any solution for this?

use this method
[self performSelector:#selector(replyTicketMethodCall) withObject:self afterDelay:5.0];
instead of this
[self replyTicketMethodCall];

Related

How to post multiple images using multipart / formdata in objective c

I am trying to post two images to an url using multipart post request in Objective C , From my code I can able to send only one image, How to send two images to the url, using multipart / form data I have tried so many example for this bur I did not get the result I want
-(void)processPostMultipartRequestNew{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *urlStr = [self.dataModel.apiUrl
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
urlStr = [urlStr
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
urlStr= [urlStr stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"];
NSURL *reqUrl = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:reqUrl];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSDictionary *requestBody = self.dataModel.requestParams2;
UIImage *imageToUpload = [requestBody objectForKey:keyUploadImage];
NSDictionary *requestBody2 = self.dataModel.requestParams;
UIImage *imageToUpload2 = [requestBody2 objectForKey:keyUploadImage];
if(requestBody){
NSData *imageData = UIImageJPEGRepresentation(imageToUpload, 0);//no compression by default
NSData *imageData2 = UIImageJPEGRepresentation(imageToUpload2, 0);
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: attachment; name=\"uploadedfile1\"; filename=\".jpeg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: attachment; name=\"uploadedfile2\"; filename=\".jpeg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[NSData dataWithData:imageData2]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// Text parameter1
NSString *param1 = #"111";
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"SyncId\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:param1] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
}
[request setHTTPShouldHandleCookies:NO];
[request setHTTPMethod:REQUEST_TYPE_POST];
[request setTimeoutInterval:60*4];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSLog(#"completionHandler with response:%#",[NSHTTPURLResponse localizedStringForStatusCode:[(NSHTTPURLResponse*)response statusCode]]);
NSLog(#"reponse: %ld",(long)[(NSHTTPURLResponse*)response statusCode]);
NSInteger status = [(NSHTTPURLResponse*)response statusCode];
if(error){
NSLog(#"http request error: %#", error.localizedDescription);
// handle the error
}
else{
if (status == 201){
// handle the success
}
else{
NSLog(#"error");
} // handle the error
}
if(!data || data == nil)
return ;
NSLog(#"%#",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
NSDictionary *resultDict =(NSDictionary *) [NSJSONSerialization
JSONObjectWithData:data options:NSJSONReadingAllowFragments
error:&error];
//NSDictionary *resultDict =(NSDictionary *) [NSJSONSerialization JSONObjectWithStream:data options:kNilOptions error:&error];
self.dataModel.responseData =resultDict;
NSLog(#"error is %#",error);
NSLog(#"data is %#",data);
{
if(!data || data == nil)
return ;
NSLog(#"%#",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
//for failed case
if(error || error != nil){
self.dataModel.responseFailed = YES;
self.dataModel.error = error;
NSLog(#"Result in error case %#",[[error userInfo] objectForKey:#"NSDebugDescription"]);
[self.reciever performSelectorOnMainThread:self.callBack withObject:self.dataModel waitUntilDone:YES];
}
else{
self.dataModel.responseFailed = NO;
self.dataModel.error = nil;
NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if(!([response rangeOfString:#".jpg"].location==NSNotFound))
{
NSString *res=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
self.dataModel.responseData =res;
[self.reciever performSelectorOnMainThread:self.callBack withObject:self.dataModel waitUntilDone:YES];
}
}
}
self.executing = NO;
[self setFinishedState:YES];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
[self.reciever performSelectorOnMainThread:self.callBack withObject:self.dataModel waitUntilDone:YES];
}];
}
Is this a right way to do? if not how can I get success in this. Thanks in advance.
Yes you can like this
Edit
///////////////////////////////
// Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept.
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:#"ios" forKey:#"device_type"];
[_params setObject:#"user" forKey:#"type"];
[_params setObject:"iddddd" forKey:#"user_id"];
// 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
// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:#"http........"];
// 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 allKeys]) {
[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 txt data
/////////////////////////////
NSArray *allImagesData= #[UIImagePNGRepresentation(imageToUpload) ,UIImagePNGRepresentation(imageToUpload2)];
NSLog(#"files array before %#", allImagesData);
for (int i=0; i<[allImagesData count]; i++)
{
NSString*filename=[NSString stringWithFormat:#"image%d.jpeg",i+1];
NSString* FileParamConstant = [NSString stringWithFormat:#"image%d",i+1];
NSData *imageData = allImagesData[i];
if (imageData)
{
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"%#\"\r\n", FileParamConstant,filename] 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]];
}
U can do like this:
-(void)PostUrlCall_Multipart_Image:(NSString *)IN_URL Param:(NSDictionary*)IN_Param Image:(UIImage *)image
{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
[manager POST:IN_URL parameters:IN_Param constructingBodyWithBlock:^(id<AFMultipartFormData> formData){
[formData appendPartWithFileData:UIImageJPEGRepresentation(image, 1.0) name:#"image" fileName:#"image" mimeType:#"image/jpeg"];
}
progress:nil
success:^(NSURLSessionDataTask *task, id responseObject) {
m_Status=1;
self.dic_Response = (NSDictionary *)responseObject;
[[NSNotificationCenter defaultCenter] postNotificationName:m_strPostMsg object:self];
}
failure:^(NSURLSessionTask *operation, NSError *error){
m_Status=0;
self.dic_Response=[[NSMutableDictionary alloc]init];
// [self.dic_Response setValue:#[Time_Out_Msg] forKey:#"#[Time_Out_Msg]"];
NSLog(#"Error %#",error);
[[NSNotificationCenter defaultCenter] postNotificationName:m_strPostMsg object:self];
}];
}

iOS Async Task ends and waits for 30 seconds to finish itself

i have an async sub class that finishes, and waits like 30 seconds after its done, if you can see, the nslog displays the OK answer, but it waits too long to put the same text that was displayed in the NSLOG, into the UILabel...
How can i break this?
this is the code:
-(BOOL) setParams{
response.text = #"";
//NSLog(#"Start:\r\n");
[indicator setHidden:NO];
[indicator startAnimating];
if(pngData != nil){
request = [NSMutableURLRequest new];
request.timeoutInterval = 20.0;
[request setURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
[request setValue:#"text/html,<span id=\"IL_AD4\" class=\"IL_AD\">application</span>/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:#"Accept"];
[request setValue:#"Mozilla/5.0 (Macintosh; Intel <span id=\"IL_AD10\" class=\"IL_AD\">Mac OS X</span> 10_7_5) AppleWebKit/536.26.14 (KHTML, like Gecko) Version/6.0.1 Safari/536.26.14" forHTTPHeaderField:#"User-Agent"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//Cada campo------------------------------------------------------------------------------------
NSString *keyName = #"add_product";
NSString *keyValue = #"valRichard";
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n",keyName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",keyValue] dataUsingEncoding:NSUTF8StringEncoding]];
//--------------------------------------------------------------------------------------------
//----La Imagen
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *imagePostName = #"imageToUpload";
NSString *imagePostValue = #"x-cosa.png";
[body appendData:[[NSString stringWithFormat:#"Content-Disposition:form-data; name=\"%#\"; filename=\"%#\"\r\n",imagePostName, imagePostValue] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:pngData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//---------------------------------------------------------------------------------------------
[request setHTTPBody:body];
[request addValue:[NSString stringWithFormat:#"%lu", (unsigned long)[body length]] forHTTPHeaderField:#"Content-Length"];
return TRUE;
}else{
response.text = NO_IMAGE;
return FALSE;
}
}
- (IBAction) uploadImageAsync1:(id)sender
{
[indicator setHidden:NO];
if([self setParams]){
response.text = #"uploadImageAsync1";
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:request queue:queue
completionHandler:^(NSURLResponse *urlResponse, NSData *data, NSError *error){
NSString *theAnswer =[NSString stringWithFormat:#"Finalizado: %#",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]];
NSLog(#"%#",theAnswer);
//HERE IS THE CODE WHICH TAKES LIKE A MINUTE TO EXECUTE!!!!!
[indicator stopAnimating];
[indicator setHidden:YES];
response.text = theAnswer;
//END OF THE THREE LINES THAT EXECUTES AFTER
[UIApplication sharedApplication].networkActivityIndicatorVisible = FALSE;
if (error) {
NSLog(#"error:%#", error.localizedDescription);
}
}];
}
}
UILabel is part of UIKit which is not thread-safe and should only be accessed from the main thread. The queue parameter in sendAsynchronousRequest: is the queue that the completion handler gets called on, so you should pass it [NSOperationQueue mainQueue] so your completion handler is called on the main thread.

Upload multiple images in one request

I want to upload more than one image in single service request. How can I do that. As of now I am able to upload single image like as
NSData *imageData = UIImageJPEGRepresentation(image, 90);
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
NSMutableData *postBody = [NSMutableData data];
// file
[postBody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithString:[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"files\"; filename=\”%#\”\r\n”,#“imagename”]] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[NSData dataWithData:imageData]];
[postBody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
Now I want to upload two images to server how can I do that.
Your answer is here. It's tested and I am using this below methods to upload multiple image along with other parameters.
- (void)uploadMultipleImageInSingleRequest
{
NSString *returnString;
NSDictionary *aParametersDic; // It's contains other parameters.
NSDictionary *aImageDic; // It's contains multiple image data as value and a image name as key
NSString *urlString; // an url where the request to be posted
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request= [[NSMutableURLRequest alloc] initWithURL:url] ;
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *postbody = [NSMutableData data];
NSString *postData = [self getHTTPBodyParamsFromDictionary:aParametersDic boundary:boundary];
[postbody appendData:[postData dataUsingEncoding:NSUTF8StringEncoding]];
[aImageDic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if(obj != nil)
{
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"PostedImage\"; filetype=\"image/png\"; filename=\"%#\"\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:obj]];
}
}];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
}
.
-(NSString *) getHTTPBodyParamsFromDictionary: (NSDictionary *)params boundary:(NSString *)boundary
{
NSMutableString *tempVal = [[NSMutableString alloc] init];
for(NSString * key in params)
{
[tempVal appendFormat:#"\r\n--%#\r\n", boundary];
[tempVal appendFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n%#",key,[params objectForKey:key]];
}
return [tempVal description];
}
One option use AFNetworking to upload multiple images
//create image data
UIImage *image = ......
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
UIImage *image2 = ......
NSData *imageData2 = UIImageJPEGRepresentation(image2, 0.5);
//Now add to array and also create array of images data
NSArray *arrImagesData = [NSArray arrayWithObjects:imageData,imageData2,nil];
//Create manager
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//parameters if any
NSDictionary *parameters = .......
//Now post
[manager POST:#"your url here" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//add img data one by one
for(int i=0; i<[arrImagesData count];i++)
{
NSData *imageData = arrImagesData[i];
NSString *strName = [NSString stringWithFormat:#"name%d",i]
[formData appendPartWithFormData:imageData name:strName];
}
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"------VohpleBoundary4QuqLuM1cE5lMwCy";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
[parameters setValue:#"IOS Testing" forKey:#"subject"];
[parameters setValue:#"Message" forKey:#"message"];
for (NSString *param in parameters) {
[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", [parameters objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
NSMutableArray *multipleArray=[[NSMutableArray alloc] init];
[multipleArray addObject:[UIImage imageNamed:#"images.jpeg"]];
[multipleArray addObject:[UIImage imageNamed:#"pic3.png"]];
for (int i=0; i<multipleArray.count;i++ )
{
NSData *imageData;
imageData = UIImageJPEGRepresentation([multipleArray objectAtIndex:i], 1.0);
if (imageData)
{
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"image.jpg\"\r\n", #"uploaded_file[]"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type:image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
else
{
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request setURL:[NSURL URLWithString:BASEURL]];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
if ([httpResponse statusCode] == 200) {
NSLog(#"success");
}
}];
}
#define kStartTag #"--%#\r\n"
#define kEndTag #"\r\n"
#define kContent #"Content-Disposition: form-data; name=\"%#\"\r\n\r\n"
#define kBoundary #"---------------------------14737809831466499882746641449"
-(void)uploadImageonServers
{
NSMutableURLRequest *request = nil;
NSLog(#"image upload");
NSMutableData *body = [NSMutableData data];
request = [[NSMutableURLRequest alloc] init];
NSString *requestURL = [NSString stringWithFormat:#"http://192.168.1.101/gmento/index.php/api/professional/addServices"];
[request setURL:[NSURL URLWithString:requestURL]];
[request setHTTPMethod:#"POST"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",kBoundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
// user ID parameter
[body appendData:[[NSString stringWithFormat:kStartTag, kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:kContent, #"professional_id"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"1232" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:kEndTag] dataUsingEncoding:NSUTF8StringEncoding]];
// Grop ID parameter
[body appendData:[[NSString stringWithFormat:kStartTag, kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:kContent, #"title"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"test" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:kEndTag] dataUsingEncoding:NSUTF8StringEncoding]];
// prepration_type_id parameter
[body appendData:[[NSString stringWithFormat:kStartTag, kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:kContent, #"price"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"test" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:kEndTag] dataUsingEncoding:NSUTF8StringEncoding]];
// description parameter
[body appendData:[[NSString stringWithFormat:kStartTag, kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:kContent, #"description"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"test" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:kEndTag] dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableArray *arr_images=[[NSMutableArray alloc] init];
[arr_images addObject:[UIImage imageNamed:#"1.jpg"]];
[arr_images addObject:[UIImage imageNamed:#"1.jpg"]];
for (int i=0; i<arr_images.count;i++ )
{
NSData *image_videoData;//isImageSet?imgMyProfPict.image:#""
image_videoData = UIImageJPEGRepresentation([arr_images objectAtIndex:i], 1.0);
if (image_videoData)
{
// image File
[body appendData:[[NSString stringWithFormat:kStartTag, kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=%#; filename=imageName.jpeg\r\n", #"services_image[]"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:image_videoData];
[body appendData:[[NSString stringWithFormat:kEndTag] dataUsingEncoding:NSUTF8StringEncoding]];
}
else
{
[body appendData:[[NSString stringWithFormat:kStartTag, kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
}
for (int i=0; i<arr_images.count;i++ )
{
NSData *image_videoData;//isImageSet?imgMyProfPict.image:#""
image_videoData = UIImageJPEGRepresentation([arr_images objectAtIndex:i], 1.0);
if (image_videoData)
{
// image File
[body appendData:[[NSString stringWithFormat:kStartTag, kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=%#; filename=imageName.jpeg\r\n", #"glimpses_image[]"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:image_videoData];
[body appendData:[[NSString stringWithFormat:kEndTag] dataUsingEncoding:NSUTF8StringEncoding]];
}
else
{
[body appendData:[[NSString stringWithFormat:kStartTag, kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
}
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSError *error;
id receivedData = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:&error];
NSDictionary *dicResponse = (NSDictionary *)receivedData;
if ([[dicResponse valueForKeyPath:#"status"] intValue] == 1)
{
}
else
{
}
}

Multipart request ios

post image and test using multipart, but it gave me error Additionally, a 404 Not Found
error was encountered while trying to use an ErrorDocument to handle the request ,i am not able to post please help
thanks in advance
NSMutableDictionary* post_dict = [[NSMutableDictionary alloc] init];
[post_dict setObject:Name.text forKey:#"name"];
[post_dict setObject:ContactNameTF.text forKey:#"contactname"];
[post_dict setObject:EmailTf.text forKey:#"email"];
[post_dict setObject:PasswordTF.text forKey:#"password"];
[post_dict setObject:HouseNumberTF.text forKey:#"housenumber"];
[post_dict setObject:StreetTF.text forKey:#"street"];
[post_dict setObject:cityTF.text forKey:#"city"];
[post_dict setObject:POstcodeTF.text forKey:#"postalcode"];
[post_dict setObject:ContactNumberTF.text forKey:#"contact"];
//[post_dict setObject:self.theImage forKey:#"image_url"];
NSString *urlString = #"http://www.ofertas24.net/codegen/index.php/codegen/register_post";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
// add the image form fields
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"image_url\"; filename=\"%#image.jpg\"\r\n",NameTF.text ] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:self.theImage];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// add the text form fields
for (id key in post_dict) {
NSLog(#"%#",key);
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:[post_dict objectForKey:key]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}
// close the form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// set request body
[request setHTTPBody:body];
// send the request (submit the form) and get the response
NSOperationQueue *queue =[[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
if ([result isEqualToString:#"true"]) {
[self performSelectorOnMainThread:#selector(mainViewController) withObject:nil waitUntilDone:NO];
}
else {
NSLog(#"%#",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}
}];
try this code,hope it helps you. . . . . . .. . . . . ..
NSString *baseurl = #"Enter URL here";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
//Set Params
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[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"];
// post body
NSMutableData *body = [NSMutableData data];
//Populate a dictionary with all the regular values you would like to send.
NSMutableDictionary* post_dict = [[NSMutableDictionary alloc] init];
[post_dict setObject:Name.text forKey:#"name"];
[post_dict setObject:ContactNameTF.text forKey:#"contactname"];
[post_dict setObject:EmailTf.text forKey:#"email"];
[post_dict setObject:PasswordTF.text forKey:#"password"];
[post_dict setObject:HouseNumberTF.text forKey:#"housenumber"];
[post_dict setObject:StreetTF.text forKey:#"street"];
[post_dict setObject:cityTF.text forKey:#"city"];
[post_dict setObject:POstcodeTF.text forKey:#"postalcode"];
[post_dict setObject:ContactNumberTF.text forKey:#"contact"];
[post_dict setObject:self.theImage forKey:#"image_url"];
// add params (all params are strings)
for (NSString *param in post_dict) {
[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", [post_dict objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
NSString *FileParamConstant = #"Enter Key Of Image Paramater";
NSData *imageData = UIImageJPEGRepresentation(image, 1);
//Assuming data is not nil we add this to the multipart form
if (imageData)
{
[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:imageData];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
//Close off the request with the boundary
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the request
[request setHTTPBody:body];
// set URL
[request setURL:[NSURL URLWithString:baseurl]];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
if ([result isEqualToString:#"true"]) {
[self performSelectorOnMainThread:#selector(mainViewController) withObject:nil waitUntilDone:NO];
}
else {
NSLog(#"%#",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}
}];

OCRApiService.com SDK issue?

I have a question regarding to the code that OCRApiService.com provides to devs.
This is the code they provide:
//author : Altaf A. M.
//Code Snippet to convert the captured/picker'd (sic) image via OCRApiService
//Input parameter: UIImage
//output parameter: NSString
//updates possible(rather necessary): integrate it asynchronously
- (NSString *) upload:(UIImage *)myImage
{
NSString *urlString = #"http://api.ocrapiservice.com/1.0/rest/ocr";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
// file
// NSData *imageData = UIImagePNGRepresentation(myImage);
NSData *imageData = UIImageJPEGRepresentation(myImage, 1.0);
[body appendData:[[NSString stringWithFormat:#"--%#", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: attachment; name=\"image\"; filename=\".jpg\""] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithString:#""] dataUsingEncoding:NSUTF8StringEncoding]];
// Text parameter1
NSString *param1 = #"en";
[body appendData:[[NSString stringWithFormat:#"--%#", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"language\""] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:param1] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#""] dataUsingEncoding:NSUTF8StringEncoding]];
// Another text parameter
NSString *param2 = #"YOUR_API_KEY";
[body appendData:[[NSString stringWithFormat:#"--%#", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"apikey\""] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:param2] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#""] dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// set request body
[request setHTTPBody:body];
//return and test
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnedString = [[[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding] autorelease];
// NSLog(#"received string = %#", returnString);
// UIAlertView *returnedText = [[UIAlertView alloc] initWithTitle:#"Returned Text" message:[NSString stringWithFormat:#"%#", returnString] delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
// [returnedText show ];
// [returnedText release];
return returnedString;
}
I put in my API Key but the problem is whenever I call this method, I get
received string = HTTP/1.1 400 Bad Request
The language parameter is missing
According to the docs, I have set the language correctly but I am not sure why it is still coming up with this error message...
Thanks!
I am the owner of ocrapiservice.com.
The api is working but there is a bug in the code snippet.
Could you please open an issue on https://github.com/smart-mobile-software/ocrapiservice/issues ?
We will correct it within the week.

Resources