Uploading pdf file from iphone - ios

i have currently working on file handling application,where i have already completed image uploading using AFNetworking with multipart selection from camera as well as gallery.
but my question is how can i select a pdf file from device[iPhone]?
I would greatly appreciate it if you kindly give me some Answer. Thank You in Advanced.
Here is my image uploading code..
AFHTTPRequestOperationManager *man = [[AFHTTPRequestOperationManager alloc]init];
man.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
int i=0;
[self dispLoaderOnView:self.view loaderText:#"Loading.."];
for(i=0 ; i< selectedImages.count; i++)
{
NSData *imageData = UIImagePNGRepresentation([selectedImages objectAtIndex:i]);
AFHTTPRequestOperation *op = [man POST:FileUpload parameters:#{
#"queryid":#"37",
#"txtFilesQuery[]":imageData,
#"selFileType[]":self.textFieldChooseFile.text,
}
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"txtFilesQuery[]" fileName:[fileNamearray objectAtIndex:i] mimeType:#"image/png"];
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"Success: %# ***** %#", operation.description, operation.responseString);
if(i==selectedImages.count-1)
{
[self hideHUDLoader];
}
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"File Uploaded" message:#"Suucessfully.." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];
[op start];
}

NSData *imageData = UIImagePNGRepresentation([selectedImages objectAtIndex:i]);
replace this code by following line
NSData *myData = [NSData dataWithContentsOfFile:[selectedImages objectAtIndex:i]];
and
[formData appendPartWithFileData:imageData name:#"txtFilesQuery[]" fileName:[fileNamearray objectAtIndex:i] mimeType:#"image/png"];
Replace this code by following
[formData appendPartWithFileData:imageData name:#"txtFilesQuery[]" fileName:[fileNamearray objectAtIndex:i] mimeType:#"application/pdf"];
may this help u.......!!!!!
let me know if it help u.

Related

Upload 5 images to server using AFNetworking [duplicate]

This question already has answers here:
AFNetworking multiple files upload
(3 answers)
Closed 6 years ago.
I used Afnetworking in my app,I need to post 5 images to server, 5 images as array, this array was one of my **request parameters.
this is correct way or wrong one, there is any one more performance than it ? -
(IBAction)sPActionButton:(id)sender {
NSUserDefaults *def=[NSUserDefaults standardUserDefaults];
NSString * language=[def objectForKey:#"Language"];
NSString * deviceToken=[def objectForKey:#"dT"];
[par setObject:deviceToken forKey:#"dT"];
NSString *check=[def objectForKey:#"Log"];
[par setObject:check forKey:#"aT"];
//---------------------------------------------
NSString * apiKey=APIKEY;
[par setObject:apiKey forKey:#"aK"];
[par setObject:language forKey:#"lG"];
NSMutableArray *images = [NSMutableArray arrayWithCapacity:10];
for (int x=0; x<_chosenImages.count; x++) {
NSData *imageData = UIImageJPEGRepresentation(_chosenImages[x], 0.5);
NSLog(#"%#",imageData);
NSString *str=[Base64 encode:imageData];
[images addObject:str];
}
NSLog(#"%#",images);
[par setObject:images forKey:#"image[array]"];
if ([self validateAllFields]) {
NSLog(#"par = %#",par);
//-----------------------------------------------
[MBProgressHUD showHUDAddedTo:self.view animated:NO];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:[NSString stringWithFormat:#"%#/sellPrp?",BASEURl] parameters:par
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"JSON: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Data"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
[MBProgressHUD hideHUDForView:self.view animated:NO];
}];
}
}
- (void)prepareForImagePosting
{
if (imageCount < self.arrAllPostImages.count)//arrAllPostImages array contains images for posting and imageCount acts as iterator
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init]; //Prepare the dictionary which contains image for posting
[dict setObject:#"1" forKey:#"upload"];
[dict setObject:[[self.arrAllPostImages objectAtIndex:imageCount]objectForKey:#"SelectedPhoto"] forKey:#"post_image"];
[self postImage:dict];
}
else
return;
}
- (void)postImage: (NSMutableDictionary *)dictPostImages
{
NSError *error = nil;
NSString *url = POSTIMAGELINK;
NSMutableDictionary *postDict = [[NSMutableDictionary alloc]init];
[postDict setObject:[dictPostImages objectForKey:#"upload"] forKey:#"upload"];
NSData *jsonRequestDict = [NSJSONSerialization dataWithJSONObject:postDict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonCommand = [[NSString alloc] initWithData:jsonRequestDict encoding:NSUTF8StringEncoding];
NSLog(#"***jsonCommand***%#",jsonCommand);
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:jsonCommand,#"requestParam", nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
if (isEnteredInFailureBlock == NO)
{
//here Image is posted
NSData *postPicData=UIImageJPEGRepresentation([dictPostImages objectForKey:#"post_image"], 0.5) ;
[formData appendPartWithFileData:postPicData
name:#"post_image"
fileName:[NSString stringWithFormat:#"image%d.jpg",imageCount]
mimeType:#"image/*"];
}
else
{
}
} success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSError *error = nil;
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"Request Successful, response '%#'", responseStr);
NSMutableDictionary *jsonResponseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
NSLog(#"Response Dictionary:: %#",jsonResponseDict);
if ([[jsonResponseDict objectForKey:#"status"] intValue] == 1)
{
if (isEnteredInFailureBlock == NO)
{
[self.arrSuccessfullyPostedImagesDetails addObject:jsonResponseDict];
if (appDel.successfullImgPostingCount == appDel.totalPostingImagesCount)
{
}
else
{
appDel.successfullImgPostingCount++;
imageCount++;
[self prepareForImagePosting];
}
}
else
{
self.arrSuccessfullyPostedImagesDetails = [[NSMutableArray alloc]init];
appDel.successfullImgPostingCount = 0;
appDel.totalPostingImagesCount = 0;
imageCount = 0;
return;
}
}
else
{
self.arrSuccessfullyPostedImagesDetails = [[NSMutableArray alloc]init];
appDel.successfullImgPostingCount = 0;
appDel.totalPostingImagesCount = 0;
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Request Error: %#", error);
isEnteredInFailureBlock = YES;
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Alert!" message:#"Posting Unsuccessful" delegate:nil cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alert show];
// if image is not successfully posted then the server is informed with #"upload" #"0" so that the entire post is deleted from server
NSMutableDictionary *failureDict = [[NSMutableDictionary alloc]init];
[failureDict setObject:#"0" forKey:#"upload"];
[self postImage:failureDict];
}];
}

Jsonobject + Image Multipart AFNetworking

We are trying to send multi-part request to server using AFNetworking. We need to send one json object and two image files. Following is the curl request for same.
curl -X POST http://localhost:8080/Circle/restapi/offer/add -H "Content-Type: multipart/form-data" -F "offerDTO={"code": null,"name": "Merry X'Mas - 1","remark": "25% discount on every purchase","validityDate": "22-12-2014","domainCode": "DO - 1","merchantCode": "M-4","isApproved": false,"discountValue": 25,"discountType": "PERCENTAGE"};type=application/json" -F "image=#Team Page.png;type=image/png" -F "letterhead=#Team Page.png;type=image/png"
I know this should be fairly easy as I've implemented the server as well as android code for same. And my friend is working on iOS part of this. Also I searched a lot on google, but did not get anything useful. So, I know its against the rules of StackOverflow, but can you guys give me the code for same using AfNetworking? If not please redirect me to examples on same lines.
Edit:
Please find below code that we tried:
UIImage *imageToPost = [UIImage imageNamed:#"1.png"];
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
offerDTO = [[NSMutableDictionary alloc]init];
[offerDTO setObject(angry)"" forKey:#"code"];
[offerDTO setObject:[NSString stringWithFormat:#"Testing"] forKey:#"discountDiscription"];
[offerDTO setObject:[NSString stringWithFormat:#"Test"] forKey:#"remark"];
[offerDTO setObject:#"07-05-2015" forKey:#"validityDate"];
[offerDTO setObject:#"C-7" forKey:#"creatorCode"];
[offerDTO setObject:#"M-1" forKey:#"merchantCode"];
[offerDTO setObject:[NSNumber numberWithBool:true] forKey:#"isApproved"];
[offerDTO setObject:#"2.4" forKey:#"discountValue"];
[offerDTO setObject:[NSString stringWithFormat:#"FREE"] forKey:#"discountType"];
NSURL *urlsss = [NSURL URLWithString:#"http://serverurl:8180"];
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:urlsss];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST"
path:#"/restapi/offer/add" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData)
{
NSData *myData = [NSJSONSerialization dataWithJSONObject:offerDTO
options:NSJSONWritingPrettyPrinted
error:NULL];
[formData appendPartWithFileData:imageData name:#"image"
fileName:#"image.jpg"
mimeType:#"image/jpeg"];
[formData appendPartWithFileData:imageData name:#"letterhead"
fileName:#"image.jpg"
mimeType:#"image/jpeg"];
[formData appendPartWithFormData:myData name:#"offerDTO"];
}
];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *jsons = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
}
failure:^(AFHTTPRequestOperation operation, NSError error)
{
NSLog(#"error: %#", [operation error]);
}
];
A couple of observations:
Your example is AFNetworking 1.x. AFNetworking 3.x rendition might look like:
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:#"1" withExtension:#"png"];
// If you need to build dictionary dynamically as in your question, that's fine,
// but sometimes array literals are more concise way if the structure of
// the dictionary is always the same.
// Also note that these keys do _not_ match what are present in the `curl`
// so please double check these keys (e.g. `discountDiscription` vs
// `discountDescription` vs `name`)!
NSDictionary *offerDTO = #{#"code" : #"",
#"discountDescription" : #"Testing",
#"remark" : #"Test",
#"validityDate" : #"07-05-2015",
#"creatorCode" : #"C-7",
#"merchantCode" : #"M-1",
#"isApproved" : #YES,
#"discountValue" : #2.4,
#"discountType" : #"FREE"};
// `AFHTTPSessionManager` is AFNetworking 3.x equivalent to `AFHTTPClient` in AFNetworking 1.x
NSURL *baseURL = [NSURL URLWithString:#"http://serverurl:8180"];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
// The `POST` method both creates and issues the request
[manager POST:#"/restapi/offer/add" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
NSError *error;
BOOL success;
success = [formData appendPartWithFileURL:fileURL
name:#"image"
fileName:#"image.jpg"
mimeType:#"image/png"
error:&error];
NSAssert(success, #"Failure adding file: %#", error);
success = [formData appendPartWithFileURL:fileURL
name:#"letterhead"
fileName:#"image.jpg"
mimeType:#"image/png"
error:&error];
NSAssert(success, #"Failure adding file: %#", error);
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:offerDTO options:0 error:&error];
NSAssert(jsonData, #"Failure building JSON: %#", error);
// You could just do:
//
// [formData appendPartWithFormData:jsonData name:#"offerDTO"];
//
// but I now notice that in your `curl`, you set the `Content-Type` for the
// part, so if you want to do that, you could do it like so:
NSDictionary *jsonHeaders = #{#"Content-Disposition" : #"form-data; name=\"offerDTO\"",
#"Content-Type" : #"application/json"};
[formData appendPartWithHeaders:jsonHeaders body:jsonData];
} progress:^(NSProgress * _Nonnull uploadProgress) {
// do whatever you want here
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"responseObject = %#", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"error = %#", error);
}];
You are creating an operation here, but never add it to a queue to start it. I assume you do that elsewhere. It's worth noting that AFHTTPSessionManager doesn't support operations like the deprecated AFHTTPRequestOperationManager or AFHTTPClient used to. The above code just starts the operation automatically.
Note, AFNetworking now assumes the response will be JSON. Given that your code suggests the response is JSON, then note that no JSONObjectWithData is needed, as that's done for you already.
Right now your code is (a) creating UIImage; (b) converting it back to a NSData; and (c) adding that to the formData. That is inefficient for a number of reasons:
Specifically, by taking the image asset, loading it into a UIImage, and then using UIImageJPEGRepresentation, you may be making the resulting NSData considerably larger than the original asset. You might consider just grabbing the original asset, bypassing UIImage altogether, and sending that (obviously, if you're sending PNG, then change the mime-type, too).
The process of adding NSData to the request can result in larger memory footprint. Often if you supply a file name, it can keep the peak memory usage a bit lower.
you can pass your NSdictionary directly to manger post block in parametersfield
UIImage *imageToPost = [UIImage imageNamed:#"1.png"];
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
NSDictionary *offerDTO = #{#"code" : #"",
#"discountDescription" : #"Testing",
#"remark" : #"Test",
#"validityDate" : #"07-05-2015",
#"creatorCode" : #"C-7",
#"merchantCode" : #"M-1",
#"isApproved" : #YES,
#"discountValue" : #2.4,
#"discountType" : #"FREE"};
NSURL *baseURL = [NSURL URLWithString:#"http://serverurl:8180"];
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
[manager POST:#"/restapi/offer/add" parameters:offerDTO constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"image"
fileName:#"image.jpg"
mimeType:#"image/jpeg"];
[formData appendPartWithFileData:imageData name:#"letterhead"
fileName:#"image.jpg"
mimeType:#"image/jpeg"];
[formData appendPartWithHeaders:jsonHeaders body:jsonData];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"responseObject = %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error = %#", error);
}]
;

Capture Upload Image Failed iOS

I m trying to upload image through AFNetworking.
Following is the way I try to save image in an array. Image uploading starts, but right after the 1.1% of upload it stops uploading without any error. No Idea what is happening.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissViewControllerAnimated:YES completion:nil];
UIImage *chosenImage = info[UIImagePickerControllerOriginalImage];
NSData *imageData=UIImagePNGRepresentation(chosenImage);
ImageObject *imageObject=[[ImageObject alloc]init];
imageObject.image=chosenImage;
imageObject.imageData=imageData;
imageObject.imageUploadStatus=FALSE;
imageObject.isUploaded=FALSE;
[imageObject setDescription:#""];
[imageDataArray addObject:imageObject];
}
After this I upload image with Following method.
-(void)uploadPicturesAndVides:(NSMutableArray *)_list descriptions:(NSMutableArray *)_description categoryID:(NSString *)_catID categoryName:(NSString *)_categoryName index:(NSInteger)_index{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager.requestSerializer setValue:[SettingValues getRSFToken] forHTTPHeaderField:#"_csrf"];
[manager.requestSerializer setValue:#"USER_Agent_Value" forHTTPHeaderField:#"User-Agent"];
NSString *imageUrl;
imageUrl=[NSString stringWithFormat:#"%#/user/upload/photo",BASE_SERVER_ADDRESS];
NSMutableArray *tempArray=[[NSMutableArray alloc] init];
for (ImageObject *object in _list) {
[tempArray addObject:[object description]];
}
NSString *descriptions;
descriptions=[tempArray componentsJoinedByString:#","];
NSDictionary *parameters = #{#"descriptionImage":descriptions,#"subcategoryId":_catID,#"subcategoryName":_categoryName,#"_csrf": [SettingValues getRSFToken]};
AFHTTPRequestOperation *op = [manager POST:imageUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSInteger count=_index;
for (ImageObject *object in _list) {
NSString *imageName = [NSString stringWithFormat:#"IMG00%zd.png",count];
[formData appendPartWithFileData:object.imageData name:#"files" fileName:imageName mimeType:#"image/png"];
}
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
[SettingValues setImageUploadStatus:TRUE];
[self uploadingRequestSuccessfulWithObject:responseObject reqestName:#"picture" index:_index];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
[op setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
double percentDone = (double)totalBytesWritten / (double)totalBytesExpectedToWrite;
[self goBackTouploadingControllerWithProgressResult:percentDone index:_index];
}];
cancelManager=op;
[op start];
}
Following is the image and its progress stays here! no success no failure. :(
Problem is that code works when I upload image through Camera Roll, But when I capture image, it did not.
I put a NSLog(#"progress updated(percentDone) : %f", percentDone); in Progress Block and I found the following logs
2015-02-07 13:07:22.854 APP_Name[2069:60b] progress updated(percentDone) : 0.002105
2015-02-07 13:07:22.858 APP_Name[2069:60b] progress updated(percentDone) : 0.004210
2015-02-07 13:07:22.860 APP_Name[2069:60b] progress updated(percentDone) : 0.006315
2015-02-07 13:07:22.861 APP_Name[2069:60b] progress updated(percentDone) : 0.008413
and then every thing stops.
In Failure block I put following log
NSLog(#"Error: %# ***** %#", operation.responseString, error);
Never executed :(

Error when uploading photo with AFNetworking

I am uploading a photo using AFNetworking and I am getting the infamous "request body stream exhausted" error.
This is my code:
(_manager is a AFHTTPRequestOperationManager)
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
AFHTTPRequestOperation *operation = [_manager POST:address parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"file" fileName:#"image.jpg" mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success!");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(#"Written: %lld", totalBytesWritten);
}];
I get the error on both my iPhone 5S and my iPhone 4, both using wifi and 4G/3G. The issue is consistent and occurs every time, just when the upload is suppose to finish. The weird thing is that it use to work on these phones as well, but some days ago I suddenly started getting the error. Also, my colleague has no problems on his iPhone 5, both on wifi and 4G, running the same code. All phones run iOS 7.
I know that some people are getting this error when on 3G, and the solution in that situation is to use the throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes delay:(NSTimeInterval)delay method. However, this has had no affect in my case, and I get the error both on wifi and mobile.
I am able to perform the upload using curl from my computer which is on the same network.
I finally found a solution in this answer:
https://stackoverflow.com/a/21304062/569507
However, in stead of subclassing the AFHTTPRequestOperation as suggested, I simply made a category on it (or actually on its parent class AFURLConnectionOperation which implements the NSURLConnectionDataDelegate protocol) that contains the connection:needNewBodyStream method. This is all that is needed. The rest of my code remains unaltered.
AFURLConnectionOperation+Recover.h
#import "AFURLConnectionOperation.h"
#interface AFURLConnectionOperation (Recover)
- (NSInputStream *)connection:(NSURLConnection *)connection needNewBodyStream:(NSURLRequest *)request;
#end
AFURLConnectionOperation+Recover.m
#import "AFURLConnectionOperation+Recover.h"
#implementation AFURLConnectionOperation (Recover)
- (NSInputStream *)connection:(NSURLConnection *)connection needNewBodyStream:(NSURLRequest *)request
{
if ([request.HTTPBodyStream conformsToProtocol:#protocol(NSCopying)]) {
return [request.HTTPBodyStream copy];
}
return nil;
}
#end
NSData *imageData = UIImageJPEGRepresentation(img,1.0);
long long testBytes = 0;
for (int i=0; i<[arrImages count];i++)
{
UIImage *img =[arrImages objectAtIndex:i];
img=[AppManager scaleDownImage:img];
NSData *imageData1 = UIImageJPEGRepresentation(img,1.0);
testBytes +=[imageData1 length]+130;
}
AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
NSMutableURLRequest *request =
[serializer multipartFormRequestWithMethod:#"POST" URLString:[NSString stringWithFormat:#"%#%#",kBaseURL,kChallengeURL] parameters:aDic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData
name:kProfileImage
fileName:#"myimage.jPEG"
mimeType:#"image/jpeg"];
}
error:nil];
//
// [serializer multipartFormRequestWithMethod:#"POST" URLString:[NSString stringWithFormat:#"%#%#",kBaseURL,kChallengeURL]
// parameters:aDic
// constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
// [formData appendPartWithFileData:imageData
// name:#"attachment"
// fileName:#"myimage.jpg"
// mimeType:#"image/jpeg"];
// }];
// 3. Create and use `AFHTTPRequestOperationManager` to create an `AFHTTPRequestOperation` from the `NSMutableURLRequest` that we just created.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFHTTPRequestOperation *operation =
[manager HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
if ([[responseObject objectForKey:kStatus] intValue]==1)
{
NSArray *arrImages = [app.dicCreateChallangeDetail objectForKey:kProfileImage];
if ([arrImages count]==1)
{
[AppManager sharedManager].enCheckCreateService = eCreateWebserviceInStopped;
[[NSNotificationCenter defaultCenter]postNotificationName:kNotificationEnableTabBarButton object:nil userInfo:nil];
self.view.userInteractionEnabled = YES;
self.navigationItem.leftBarButtonItem.enabled = YES;
[self performSelector:#selector(goToHomeScreen) withObject:nil afterDelay:0.0];
}
else if ([arrImages count]>1)
{
[self uploadRestImages:[responseObject objectForKey:kChallengeId]];
}
}
else
{
[AppManager sharedManager].enCheckCreateService = eCreateWebserviceInStopped;
self.view.userInteractionEnabled = YES;
self.navigationItem.leftBarButtonItem.enabled = YES;
[Utils showAlertView:kAlertTitle message:[responseObject objectForKey:kMessage] delegate:nil cancelButtonTitle:kAlertBtnOK otherButtonTitles:nil];
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error){
//NSLog(#"Failure %#", error.description);
[AppManager sharedManager].enCheckCreateService = eCreateWebserviceInStopped;
self.view.userInteractionEnabled = YES;
self.navigationItem.leftBarButtonItem.enabled = YES;
[Utils showAlertView:kAlertTitle message:#"Failed. Try again" delegate:nil cancelButtonTitle:kAlertBtnOK otherButtonTitles:nil];
[[NSNotificationCenter defaultCenter]postNotificationName:kNotificationEnableTabBarButton object:nil userInfo:nil];
}];
// 4. Set the progress block of the operation.
[operation setUploadProgressBlock:^(NSUInteger __unused bytesWritten,
long long totalBytesWritten,
long long totalBytesExpectedToWrite) {
NSLog(#"Wrote %lld/%lld", totalBytesWritten, totalBytesExpectedToWrite);
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:#"%lld",totalBytesWritten],#"written",[NSString stringWithFormat:#"%lld",totalBytesExpectedToWrite],#"Totlal",nil];
[[NSNotificationCenter defaultCenter]postNotificationName:kNotificationRefreshHomePage object:dict userInfo:nil];
}];
// 5. Begin!
[operation start];

Uploading images to server

I am trying to upload an image to a server (that is already built) and I am getting errors like Request has timed out. Other methods of sending text and fetch data from the server are working properly. However, sending an image I found it hard to do it.
I am using the following code at the moment:
-(void)uploadImage:(NSData*)image callbackBlock: (void (^)(BOOL success)) callbackBlock
{
NSString *path = [NSString stringWithFormat:#"upload"];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:image, #"image", nil];
[params addEntriesFromDictionary:self.sessionManager.authParameters];
NSMutableURLRequest *request = [self multipartFormRequestWithMethod:#"POST" path:path parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData){
[formData appendPartWithFormData:image name:#"Image"];
}];
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"!!!Response object: %#",responseObject);
callbackBlock(YES);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#",error.description);
callbackBlock(NO);
}];
[self enqueueHTTPRequestOperation:operation];
}
Do you have any idea what the problem is? Can you give me some suggestions or possible errors on the above code.
Thank you very much.
You can send your image as a base64 encoded text... This should work.
You can use this category to create base64 encoded image:
https://github.com/l4u/NSData-Base64

Resources