currently i am working on image uploading in ios application and here is my code
AFHTTPRequestOperationManager *man = [[AFHTTPRequestOperationManager alloc]init];
man.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
NSData *imageData = UIImagePNGRepresentation(self.imageView.image);
AFHTTPRequestOperation *op = [man POST:AddGroup parameters:#{ #"userid":#"6",
#"name":self.txtGroupName.text
#"description":self.textViewGroupDescription.text,
#"image":imageData }
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"image" fileName:filename mimeType:#"image/png"];
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"Success: %# ***** %#", operation.description, operation.responseString);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Imani" message:#"New Group Succesfully Created.." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] ;
[alertView show];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];
[op start];
now i am getting response from successfully from json but image data are passing null in to server any one have idea ?
Thank you.
try this cede to upload image on server.
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:#"your api link"]];
NSData *imageData = UIImageJPEGRepresentation(self.imgPost.image, 0.5);
NSDictionary *parameters = #{#"param": #"value",
#"param2" : #"value2"
};
AFHTTPRequestOperation *op = [manager POST:#"/api/store/posts/format/json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//do not put image inside parameters dictionary as I did, but append it!
[formData appendPartWithFileData:imageData name:#"file" fileName:[NSString stringWithFormat:#"njoyful_%f.jpg",[NSDate timeIntervalSinceReferenceDate]] mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %# ***** %#", operation.responseString, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];
[op start];
I'm not familiar with AFHTTPRequestOperation so i'll just give you something i'm using that creates json request.
- (NSURLRequest *)convertToRequest:(NSString *)stringURL withDictionary:(NSDictionary *)dictionary
{
NSError *error = nil;
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
NSURL *url = [NSURL URLWithString:stringURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: JSONData];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept-Encoding"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[JSONData length]] forHTTPHeaderField:#"Content-Length"];
return request;
}
Please check my answer here
This also work for multi image upload. Cheers! :)
Related
I'm working on an app in which I need to upload file to some server, and I'm using AFNetworking to upload file.
All work fine except if file size is short like 2mb and if more than this, server respond me error with status code 500 and doesn't upload file.
Here below is code how I am uploading.
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:lang forHTTPHeaderField:#"Accept-Language"];
[request setValue:authVal forHTTPHeaderField:#"authorization"];
[request setValue:[headerParams objectForKey:#"x-file-name"] forHTTPHeaderField:#"x-file-name"];
[request setValue:[headerParams objectForKey:#"x-convert-document"] forHTTPHeaderField:#"x-convert-document"];
[request setValue:[headerParams objectForKey:#"x-source"] forHTTPHeaderField:#"x-source"];
//convert parameters in to json data
if ([params isKindOfClass:[NSDictionary class]]) {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
options:NSJSONWritingPrettyPrinted
error:&error];
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
[request setURL:[NSURL URLWithString:action]];
[request setTimeoutInterval:200.0];
[request setHTTPMethod:#"POST"];
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:imageData];
NSLog(#"File size is : %.2f MB",(float)imageData.length/1024.0f/1024.0f);
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSInteger statusCode = [operation.response statusCode];
NSNumber *statusObject = [NSNumber numberWithInteger:statusCode];
successBlock(responseObject, statusObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}
The line of code [request setHTTPBody:imageData]; is setting NSData of image.
The same thing works on Android and its working fine but they'r using stream, first to write file into Physical path then by using stream to upload. Is this possible by using AFNetworking? or can I achieve this by using other approach too?
Looking for Suggestion.
Thanks
Note :- I have just implemented Image Upload service using AFNetworking 3.0,
-> Here kBaseURL means Base URL of server
->serviceName means Name of Service.
->dictParams means give parameters if needed, otherwise nil.
->image means pass your image.
Note :- This code written in NSObject Class and we have apply in our Project.
+ (void)requestPostUrlWithImage: (NSString *)serviceName parameters:(NSDictionary *)dictParams image:(UIImage *)image success:(void (^)(NSDictionary *responce))success failure:(void (^)(NSError *error))failure {
NSString *strService = [NSString stringWithFormat:#"%#%#",kBaseURL,serviceName];
[SVProgressHUD show];
NSData *fileData = image?UIImageJPEGRepresentation(image, 0.5):nil;
NSError *error;
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:strService parameters:dictParams constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if(fileData){
[formData appendPartWithFileData:fileData
name:#"image"
fileName:#"img.jpeg"
mimeType:#"multipart/form-data"];
}
} error:&error];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(#"Wrote %f", uploadProgress.fractionCompleted);
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
[SVProgressHUD dismiss];
if (error)
{
failure(error);
}
else
{
NSLog(#"POST Response : %#",responseObject);
success(responseObject);
}
}];
[uploadTask resume];
}
--> Now apply in our project.
UIImage *imgProfile = //Pass your image.
[WebService requestPostUrlWithImage:#"saveImageWithData" parameters:nil image:imgProfile success:^(NSDictionary *responce) {
NSString *check = [NSString stringWithFormat:#"%#",[responce objectForKey:#"status"]];
if ([check isEqualToString: #"1"]) {
//Image Uploaded.
}
else
{
//Failed to Upload.
}
} failure:^(NSError *error) {
//Error
}];
How can i send Base64 image encoded to the server using af networking. I have converted the image in to base 64 but the problem is in sending the image to the server. Iam new to ios so please help me in resolving this issue.
NSString *surl = #"https://xxxxxxxxxxxxx";
surl = [surl stringByAppendingString:userID];
NSLog(#"%#", surl);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:surl]];
[request setHTTPMethod:#"POST"];
[request setValue:#"multipart/form-data" forHTTPHeaderField:#"Accept"];
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[base64 dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postBody];
NSLog(#"postbody%#", postBody);
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
operation.responseSerializer = [AFHTTPResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON Successsss: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#",error);
NSHTTPURLResponse *response = (NSHTTPURLResponse *)operation.response;
NSLog(#"statusCode: %ld", (long)response.statusCode);
NSString* ErrorResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
NSLog(#"Error Response:%#",ErrorResponse);
}];
[[NSOperationQueue mainQueue] addOperation:operation];
}
I want to send JSON data in URL body from my IOS app to server.I searched many SO question but i can't find what i want. If anyone knows how to do with AFNetworking then please let me know.Thanks
This is my code snipped which send parameters
NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];
[parameters setValue:#"PY" forKey:#"AppSecret"];
[parameters setValue:#"IOS" forKey:#"login_provider"];
[parameters setValue:_txtemail.text forKey:#"email"];
[parameters setValue:_txtpassword.text forKey:#"password"];
[parameters setValue:#"1" forKey:#"ios_device_id"];
AFHTTPSessionManager *managertwo = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
managertwo.requestSerializer = [AFJSONRequestSerializer serializer];
[managertwo.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[managertwo POST:[NSString stringWithFormat:#"http://capemedics.co.za/Api/user_register/valid_user"] parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"success! %#",responseObject);
NSLog(#"%#",parameters);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"error: %#", error);
}];
And i am getting error in it. I want to pass JSON data like this in URL Body
{"login_provider": "IOS","email": "%#","password": ”%#“,”ios_device_id": "1"}
Try This
NSString *strData = [[NSString alloc] initWithFormat:#"{\"login_provider\": \"IOS\",\"email\": \"%#\",\"password\": \"%#\",\"ios_device_id\": \"1\"}",self.txtEmail.text,self.txtPassword.text];
NSString *strURL = #"http://capemedics.co.za/Api/user_register/valid_user"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strURL] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
[request setHTTPMethod:#"POST"];
[request setValue: #"YOUR_KEY" forHTTPHeaderField: #"AppSecret"];
[request setValue: #"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: [strData dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
if (responseObject)
{
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error){
}];
[op start];
It worked before not sure
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL
cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
[request setHTTPMethod:#"POST"];
[request setValue: #"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: [body dataUsingEncoding:NSUTF8StringEncoding]]; /// body is your son string
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON responseObject: %# ",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error localizedDescription]);
}];
[op start];
Following is my code snippet. I am getting an error while runnning this code. I have added headers as part of the request. Is that the correct way ?
__block int i=1;
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:url]];
NSDictionary *parameters = #{#"wave_Id": [inputDictionary objectForKey:#"wave_Id"]};
AFHTTPRequestOperation *op = [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
for(NSData *imageData in [inputDictionary objectForKey:#"images"])
{
[formData appendPartWithFileData:imageData name:[NSString stringWithFormat:#"file%d",i] fileName:[NSString stringWithFormat:#"abc%d.png",i] mimeType:#"image/png"];
i++;
}
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error];
NSAssert(jsonData, #"Failure building JSON: %#", error);
NSLog(#"Json Data Image Upload %#",jsonData);
NSAssert(jsonData, #"Failure building JSON: %#", error);
NSString *token = [SSKeychain passwordForService:RegistrationTokenKey account:LoggedInUserKey];
NSDictionary *jsonHeaders = #{#"Content-Disposition" : #"form-data; name=\"parameters\"",
#"Content-Type" : #"application/json",
#"Accept" : #"application/json",
#"Authorization" : token};
[formData appendPartWithHeaders:jsonHeaders body:jsonData];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %# ***** %#", operation.responseString, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];
[op start];
I need your complete method to be 100% sure, but please try writing this way and see if it helps:
__block int i = 1;
NSMutableArray *mutableOperations = [NSMutableArray array];
NSDictionary *parameters = #{#"wave_Id": [inputDictionary objectForKey:#"wave_Id"]};
for (NSData *imageData in [inputDictionary objectForKey:#"images"]) {
NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST"
URLString:url
parameters:parameters
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData
name:[NSString stringWithFormat:#"file%d",i]
fileName:[NSString stringWithFormat:#"abc%d.png",i]
mimeType:#"image/png"];
i++;
}
error:nil];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[mutableOperations addObject:operation];
}
NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:mutableOperations progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
NSLog(#"%lu of %lu images uploaded!", numberOfFinishedOperations, totalNumberOfOperations);
} completionBlock:^(NSArray *operations) {
NSLog(#"All images have been uploade!");
}];
[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];
Actually I modified the same code and its working now. Changed the "Content-Type" to "multipart/form-data".
Also added the key (parameter name) for my imagesArray in the API request to the following method
"formData appendPartWithFileData:imageData name:#"yourKey"..."
if (_isUploadImage) {
__block int i=1;
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:url]];
[manager.requestSerializer setValue:#"multipart/form-data" forHTTPHeaderField:#"Content-Type"];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
if (_shouldBeInHeader) {
NSString *token = [SSKeychain passwordForService:RegistrationTokenKey account:LoggedInUserKey];
[manager.requestSerializer setValue:[NSString stringWithFormat:#"Token %#",token] forHTTPHeaderField:#"Authorization"];
}
NSDictionary *parameters = #{#"wave_id": [inputDictionary objectForKey:#"wave_id"]};
AFHTTPRequestOperation *op = [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
for (NSData *imageData in [inputDictionary objectForKey:#"images"])
{
[formData appendPartWithFileData:imageData name:[NSString stringWithFormat:#"images"] fileName:[NSString stringWithFormat:#"abc%d.png",i] mimeType:#"image/png"];
i++;
}
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failed");
}];
[op start];
}
This is my first post in here and is not a repost, I have searched a lot in Stack Overflow for the answer, but without luck... The problem that I'm having is an intermittent error: "request body stream exhausted" with the code:-1021, I'm using AFNetworking 2.
This is what I use to create a RequestOperationManager:
- (AFHTTPRequestOperationManager *)createDefaultManager {
AFHTTPRequestOperationManager *postRequest = [[AFHTTPRequestOperationManager alloc]initWithBaseURL:[NSURL URLWithString:#"myURL"]];
postRequest.securityPolicy.allowInvalidCertificates = YES;
postRequest.responseSerializer = [AFXMLParserResponseSerializer serializer];
[postRequest.requestSerializer setValue:#"Keep-Alive" forHTTPHeaderField:#"Connection"];
[postRequest.requestSerializer setValue:#"text/xml" forHTTPHeaderField:#"Content-Type"];
[postRequest.requestSerializer setValue:#"en-US" forHTTPHeaderField:#"Content-Language"];
return postRequest;
}
Here is my post method:
- (void)postRequest:(AFHTTPRequestOperationManager *)request withURL:(NSString *)url withBody:(NSString *)body {
[request POST:url parameters:nil constructingBodyWithBlock:^(id <AFMultipartFormData>formData)
{
[formData throttleBandwidthWithPacketSize:kAFUploadStream3GSuggestedPacketSize
delay:kAFUploadStream3GSuggestedDelay];
NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
[mutableHeaders setValue:[NSString stringWithFormat:#"text/xml"] forKey:#"Content-Type"];
[mutableHeaders setValue:[NSString stringWithFormat:#"any-value"] forKey:#"User-Agent"];
[formData appendPartWithHeaders:mutableHeaders body:[NSData dataWithBytes:[body UTF8String] length:[body length]]];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
[self connectionSuccess:operation withResponse:responseObject];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[self connectionFailed:operation withError:error];
NSLog(#"Here's the request: %#", operation.request.HTTPBody);
}];
}
I don't know what is wrong in what I'm doing. That should work all the time.
Thanks,
JJ