I think its been very simple question, but i'm stuck to it quite long time. I have a function but getting some brackets issue and unable to run the code. I'm not getting where the brackets should close.
My code is,
-(void)Images{
NSString *eachImagePath;
if(_arrai.count == 0)
return;
eachImagePath = [NSString stringWithFormat:#"%#",_arrai[0]];
NSMutableDictionary *dictAddNewJobImages = [[NSMutableDictionary alloc]init];
dictAddNewJobImages[#"property_id"] = Propid;
dictAddNewJobImages[#"name"] = _arrainame;
NSString *strWebService = [NSString stringWithFormat:#"My URL"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes=[NSSet setWithObject:#"text/html"];
[manager.requestSerializer setTimeoutInterval:600.0];
[manager POST:strWebService parameters:dictAddNewJobImages constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData)
{
NSURL *filePath = [NSURL fileURLWithPath:eachImagePath];
[formData appendPartWithFileURL:filePath name:#"image" error:nil];
} progress:^(NSProgress * _Nonnull uploadProgress)
{
} success:^(NSURLSessionDataTask* _Nonnull *task, id _Nullable responseObject)
{
NSLog(#"%#",responseObject);
[_arrai removeObjectAtIndex:0];
if(_arrai.count > 0)
[self Images];
} failure:^(NSURLSessionDataTask* _Nullable task, NSError* _Nonnull error) {
NSLog(#"%#",error);
}
}
you forget to close your block }];
use
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:XXXXXX parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}]; --> add the close in failure
instead of
[manager GET:XXXXXX parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}
updated answer
-(void)Images{
NSString *eachImagePath;
if(_arrai.count == 0)
return;
eachImagePath = [NSString stringWithFormat:#"%#",_arrai[0]];
NSMutableDictionary *dictAddNewJobImages = [[NSMutableDictionary alloc]init];
dictAddNewJobImages[#"property_id"] = Propid;
dictAddNewJobImages[#"name"] = _arrainame;
NSString *strWebService = [NSString stringWithFormat:#"My URL"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes=[NSSet setWithObject:#"text/html"];
[manager.requestSerializer setTimeoutInterval:600.0];
[manager POST:strWebService parameters:dictAddNewJobImages constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData)
{
NSURL *filePath = [NSURL fileURLWithPath:eachImagePath];
[formData appendPartWithFileURL:filePath name:#"image" error:nil];
} progress:^(NSProgress * _Nonnull uploadProgress)
{
} success:^(NSURLSessionDataTask* _Nonnull *task, id _Nullable responseObject)
{
NSLog(#"%#",responseObject);
[_arrai removeObjectAtIndex:0];
if(_arrai.count > 0)
[self Images];
} failure:^(NSURLSessionDataTask* _Nullable task, NSError* _Nonnull error) {
NSLog(#"%#",error);
}]; -- > close your block here
}
Related
i am sending it with parameter but no working and in Postman Itis working see screenshot below
NSDictionary*Param=#{#"api_token":#"6fkgRh72y6L8DJi1zgYJr55zA0l3vrgnUOU3w6qFDCgX6e0QzwPLwT5D8nOHs8Ye35kFCjrAzSDNYvSsvkxJrmnMxX4iO5GXo7bgjcyKaidhmZ9SqWDEyspnsEFTFjnAX0V80FeJYZ6w8IdOpjoGNO"
};
NSData *imageData = UIImagePNGRepresentation(image);
NSString*url=[NSString stringWithFormat:#"http://asinfrastructure.com/mazad/public/api/v1/user/auction/media/upload/photo"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[manager POST:url parameters:Param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData
name:#"photo"
fileName:#"Image.png" mimeType:#"image/jpeg"];
} progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"Response: %#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: %#", error);
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] options:NSJSONReadingAllowFragments error:&error];
NSLog(#"%#",JSON);
}];
Your code Works well.
-(void)uploadImage1:(UIImage *)img Dictionary:(NSMutableDictionary *)dictParam {
NSData *imageData = UIImageJPEGRepresentation(img, 0.7);
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[manager POST:kWOJSignUPCall parameters:dictParam constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if (imageData != nil) {
[formData appendPartWithFileData:imageData
name:#"profile_image"
fileName:#"user_image.jpg"
mimeType:#"image/jpg"];
}
} progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"Response: %#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: %#", error);
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] options:NSJSONReadingAllowFragments error:&error];
NSLog(#"%#",JSON);
}];
}
OR Try This.
-(void)uploadImage1:(UIImage *)img Dictionary:(NSMutableDictionary *)dictParam {
NSData *imageData;
if (img == nil) {
}
else {
imageData = UIImageJPEGRepresentation(img, 0.7);
}
AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
requestSerializer = [AFJSONRequestSerializer serializer];
responseSerializer = [AFJSONResponseSerializer serializer];
NSError *__autoreleasing* error = NULL;
NSMutableURLRequest *request = [requestSerializer multipartFormRequestWithMethod:#"POST" URLString:kWOJSignUPCall parameters:dictParam constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if (imageData != nil) {
[formData appendPartWithFileData:imageData
name:#"profile_image"
fileName:#"user_image.jpg"
mimeType:#"image/jpg"];
}
} error:(NSError *__autoreleasing *)error];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = responseSerializer;
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(#"ERROR WHILE UPLOADING IMAGE = %#",error.localizedDescription);
}
else {
if ([[responseObject valueForKey:#"status"] intValue] == 1) {
NSLog(#"Image Upload Done.");
}
else {
NSLog(#"Image Upload Fails.");
}
}
}];
[uploadTask resume];
}
I want to upload pending data to a server and then download all data from the server database at the same button click. But I'm not getting how to show progress bar showing the progress of uploading/downloading.I tried using "setDownloadTaskDidWriteDataBlock" but it is never called.
My code:
-(void)asyncTask:(NSString *)strURL parameters:(NSDictionary *)dictParams success:(void (^)(NSDictionary *response))success failure:(void (^)(NSError *error))failure {
NSLog(#"parameters passed to server through services=%#",dictParams);
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// [manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript", #"text/html", nil];
[manager POST:strURL parameters:dictParams progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"inside requestPostUrl JSON: %#", responseObject);
if([responseObject isKindOfClass:[NSDictionary class]]) {
if(success) {
success(responseObject);
}
}
else {
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
if(success) {
success(response);
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if(failure) {
failure(error);
}
}];
//the below method is never triggered
[manager setDownloadTaskDidWriteDataBlock:^(NSURLSession *session,NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
CGFloat written = totalBytesWritten;
CGFloat total = totalBytesExpectedToWrite;
CGFloat percentageCompleted = written/total;
NSLog(#"percentage completed=%f",percentageCompleted);
dispatch_async(dispatch_get_main_queue(), ^{
// here is what you want
// vc.progressBarView.progress = (CGFloat)totalBytesWritten / totalBytesExpectedToWrite;
});
//Return the completed progress so we can display it somewhere else in app
// if( progressBlock){
// dispatch_async(dispatch_get_main_queue(), ^{
// progressBlock(percentageCompleted,remoteURLPath);
// });
// }
}];
Someone please help me!
Thank you!
try this code
- (void)sycLocations:(NSString *)strURL parameters:(NSDictionary *)dictParams success:(void (^)(NSDictionary *responce))success failure:(void (^)(NSError *error))failure {
__weak typeof(self) vc = self;
NSLog(#"parameters passed to server through services=%#",dictParams);
manager = [AFHTTPSessionManager manager];
// [manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript", #"text/html", nil];
[manager POST:strURL parameters:dictParams progress:^(NSProgress * _Nonnull uploadProgress){
[manager setDataTaskDidReceiveDataBlock:^(NSURLSession *session,
NSURLSessionDataTask *dataTask,
NSData *data)
{
if (dataTask.countOfBytesExpectedToReceive == NSURLSessionTransferSizeUnknown)
return;
NSUInteger code = [(NSHTTPURLResponse *)dataTask.response statusCode];
NSLog(#"status from server=%lu",(unsigned long)code);
if (!(code> 199 && code < 400))
return;
long long bytesReceived = [dataTask countOfBytesReceived];
long long bytesTotal = [dataTask countOfBytesExpectedToReceive];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"show progress status :) ................");
vc.progressBar.progress= (CGFloat)bytesReceived / bytesTotal;
});
}];
}success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if([responseObject isKindOfClass:[NSDictionary class]]) {
if(success) {
success(responseObject);
}
}
else {
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
if(success) {
success(response);
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if(failure) {
failure(error);
}
}];
}
Code for tracking upload & download progress
-(void)postUpdateV4:(NSString *)param param1:(NSString *)param1 param2:(NSString *)param2 param3:(NSString *)param3 param4:(NSString *)param4 param5:(NSString *)param5 param6:(NSString *)param6 param7:(NSString *)param7 param8:(NSString *)param8 param9:(NSString *)param9
{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager.responseSerializer setAcceptableContentTypes:[NSSet setWithArray:#[#"application/json"]]];
[manager setDataTaskDidReceiveDataBlock:^(NSURLSession *session,
NSURLSessionDataTask *dataTask,
NSData *data)
{
if (dataTask.countOfBytesExpectedToReceive == NSURLSessionTransferSizeUnknown)
return;
NSUInteger code = [(NSHTTPURLResponse *)dataTask.response statusCode];
NSLog(#"status from server=%lu",(unsigned long)code);
if (!(code> 199 && code < 400))
return;
long long bytesReceived = [dataTask countOfBytesReceived];
long long bytesTotal = [dataTask countOfBytesExpectedToReceive];
...
});
}];
[manager setTaskDidSendBodyDataBlock:^(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend)
{
double percentDone = (double)totalBytesSent / totalBytesExpectedToSend;
NSString *percentDoneString = [NSString stringWithFormat:#"%.2f", percentDone];
...
}];
[manager POST:param parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:[param1 dataUsingEncoding:NSUTF8StringEncoding] name:#"payload" fileName:#"temp.txt" mimeType:#"text/plain"]; // you file to upload
[formData appendPartWithFormData:[param2 dataUsingEncoding:NSUTF8StringEncoding]
name:#"title"];
[formData appendPartWithFormData:[param3 dataUsingEncoding:NSUTF8StringEncoding]
name:#"dateSent"];
[formData appendPartWithFormData:[param4 dataUsingEncoding:NSUTF8StringEncoding]
name:#"language"];
[formData appendPartWithFormData:[param5 dataUsingEncoding:NSUTF8StringEncoding]
name:#"changesEmailString"];
[formData appendPartWithFormData:[param6 dataUsingEncoding:NSUTF8StringEncoding]
name:#"sentBy"];
[formData appendPartWithFormData:[param7 dataUsingEncoding:NSUTF8StringEncoding]
name:#"notifTitle"];
[formData appendPartWithFormData:[param8 dataUsingEncoding:NSUTF8StringEncoding]
name:#"notifBody"];
[formData appendPartWithFormData:[param9 dataUsingEncoding:NSUTF8StringEncoding]
name:#"groupToken"];
} progress:^(NSProgress * _Nonnull uploadProgress){
} success:^(NSURLSessionDataTask *task, id responseObject) {
if(!responseObject)
{
...
}
else
{
NSDictionary *jsonDict = (NSDictionary *) responseObject;
NSString *res = [NSString stringWithFormat:#"%#", [jsonDict objectForKey:#"result"]];
...
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
...
}];
}
I need to send image as param like
URl : some API
params : {profileImage:string(file)}
Means in param list only i have to send image file as string.
i used the below code. but it is not working.
NSData *dataImage = [[NSData alloc] init];
dataImage = UIImagePNGRepresentation(selectedImage);
NSString *stringImage = [dataImage base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
NSDictionary *params = {profileImage : stringImage}
NSString *url = [NetworkRoutes postProfileImageAPIWithMobileNumber:[PTUserDetails getMobileNumber]];
self.operationManager = [AFHTTPSessionManager manager];
self.operationManager.responseSerializer = [AFJSONResponseSerializer serializer]; //
[self.operationManager.requestSerializer setAuthorizationHeaderFieldWithUsername:#“userName” password:#“some password”];
[self.operationManager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
NSError *error;
if (![formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:#"file" fileName:[path lastPathComponent] mimeType:#"image/jpg" error:&error]) {
NSLog(#"error appending part: %#", error);
}
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
your answer no need to be in afnetworking , can also be in nsurlconnection
I am getting resposne
{
response :"Please upload image file"
}
OR
Suggest me how to do like in the attached screen shot . In post man i am getting response
NSData *imgData = UIImageJPEGRepresentation(image, 1.0);
NSUInteger fileSize = [imgData length];
if(fileSize>400000)
{
float size = (float)((float)400000/(float)fileSize);
imgData = [NSData dataWithData:UIImageJPEGRepresentation(image, size)];
}
NSString *imgProfilePic = [imgData base64Encoding];
and then you can send this imgProfilePic to Webservice
If you send your image in multipart then this might be helpful and easiest way than BASE64
and also no need to convert your image into BASE64 String.
- (void)uploadImage:(UIImage*)image withParams:(NSDictionary*)paramsDict withURL:(NSString *)URL
{
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
AFHTTPRequestOperationManager *manager =
[AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:URL parameters:paramsDict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if (imageData!=nil) {
[formData appendPartWithFileData:imageData name:#"imagename" fileName:#"filename" mimeType:#"image/jpeg"];
}
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"success = %#", responseObject);
[appDelegate dismissLoading];
if ([[responseObject valueForKey:#"code"] isEqualToString:#"200"])
{
// code after success
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[appDelegate dismissLoading];
NSLog(#"error = %#", error);
}];
}
Try to send like following (one of the below) way:
1.
-(void)uploadimage{
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:#"http://your server.url"]];
NSData *imageData = UIImageJPEGRepresentation(self.avatarView.image, 0.5);
// if you want to pass another parameter with image then
NSDictionary *param = #{#"username": self.username, #"password" : self.password};
AFHTTPRequestOperation *operation = [manager POST:#"rest.of.url" parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//do not put image inside parameters dictionary, but append it!
[formData appendPartWithFileData:imageData name:paramNameForImage fileName:#"photo.jpg" mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %# ***** %#", operation.responseString, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];
[operation start];
}
2.
UIImage *image = [UIImage imageNamed:#"imageName.png"];
NSData *imageData = UIImageJPEGRepresentation(image,1);
NSString *queryStringss = [NSString stringWithFormat:#"http://your server/uploadfile/"];
queryStringss = [queryStringss stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager POST:queryStringss parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
[formData appendPartWithFileData:imageData name:#"fileName" fileName:#"imageName.png" mimeType:#"image/jpeg"];
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *dict = [responseObject objectForKey:#"Result"];
NSLog(#"Success: %# ***** %#", operation.responseString, responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];
I have used the following code but the response which i get is java.lang.NullPointerException & INTERNAL_SERVER_ERROR I tried many different methods but unable to fix it please help in fixing this.
Getting the Image from the Image picker
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
Profilebackground.image = chosenImage;
[picker dismissViewControllerAnimated:YES completion:NULL];
NSURL *resourceURL;
UIImage *image =[[UIImage alloc] init];
image =[info objectForKey:#"UIImagePickerControllerOriginalImage"];
NSURL *imagePath = [info objectForKey:#"UIImagePickerControllerReferenceURL"];
imageName = [imagePath lastPathComponent];
resourceURL = [info objectForKey:UIImagePickerControllerReferenceURL];
NSString *extensionOFImage =[imageName substringFromIndex:[imageName rangeOfString:#"."].location+1 ];
if ([extensionOFImage isEqualToString:#"JPG"])
{
imageData =UIImageJPEGRepresentation(image, 1.0);
base64 = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
extension=#"image/jpeg";
}
else
{
imageData = UIImagePNGRepresentation(image);
base64 = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
extension=#"image/png";
}
int imageSize=imageData.length/1024;
NSLog(#"imageSize--->%d", imageSize);
if (imageName!=nil) {
NSLog(#"imageName--->%#",imageName);
}
else
{
NSLog(#"no image name found");
}
Send the Image to server
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:#"https://blahblahblah.com/uploadProfileImg?userId=1" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//NSData *pngData = [[NSData alloc] initWithBase64EncodedString:base64 options:1];
[formData appendPartWithFileData:imageData
name:#"key"
fileName:imageName mimeType:extension];
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"Response: %#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
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);
}];
You can just use the appendPartWithFileData:name:fileName:mimeType: method of the AFMultipartFormData class.
For instance:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager POST:#"https://blahblahblah.com/imageupload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData
name:#"key name for the image"
fileName:photoName mimeType:#"image/jpeg"];
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"Response: %#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: %#", error);
}];
Please try the below code in AFNetworking 2.0.3
Hope this will helpful for u
- (void) createNewAccount:(NSString *)nickname accountType:(NSInteger)accountType primaryPhoto:(UIImage *)primaryPhoto
{
// Ensure none of the params are nil, otherwise it'll mess up our dictionary
if (!nickname) nickname = #"";
NSLog(#"Creating new account %#", params);
[self POST:#"accounts" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFormData:[nickname dataUsingEncoding:NSUTF8StringEncoding] name:#"nickname"];
[formData appendPartWithFormData:[NSData dataWithBytes:&accountType length:sizeof(accountType)] name:#"type"];
if (self.accessToken)
[formData appendPartWithFormData:[self.accessToken dataUsingEncoding:NSUTF8StringEncoding] name:#"access_token"];
if (primaryPhoto) {
[formData appendPartWithFileData:UIImageJPEGRepresentation(primaryPhoto, 1.0)
name:#"primary_photo"
fileName:#"image.jpg"
mimeType:#"image/jpeg"];
}
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"Created new account successfully");
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: couldn't create new account: %#", error);
}];
}
At last I made it work
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:#"https://blahblahblah.com/uploadProfileImg?userId=1" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData
name:#"key"
fileName:imageName mimeType:extension];
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"Response: %#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
NSLog(#"error: %#",error);
NSLog(#"statusCode: %ld", (long)response.statusCode);
NSString* ErrorResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
NSLog(#"Error Response:%#",ErrorResponse);
}];
I'm using AFNetworking for some GET queries. But my function always returns nil value. Where I was wrong?
+ (NSString *)getRequestFromUrl:(NSString *)requestUrl {
NSString * completeRequestUrl = [NSString stringWithFormat:#"%#%#", BASE_URL, requestUrl];
__block NSString * results;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:completeRequestUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
results = [NSString stringWithFormat:#"%#", responseObject];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
results = [NSString stringWithFormat:#"Error"];
}];
NSLog(#"%#", results);
return results;
}
Thx! Artem.
You're not seeing a result because the blocks that you pass in for success and failure run asynchronously; by the time your NSLog gets called, the web service won't have returned yet. If you move your NSLog inside of your success and failure blocks, you should see a result get output to your console.
Because of the asynchronous nature of these calls, you won't be able to simply return the value from your method. Instead, you may want to take your own block as a parameter, which you can then call when you have a result. For example:
+ (void)getRequestFromUrl:(NSString *)requestUrl withCompletion:((void (^)(NSString *result))completion
{
NSString * completeRequestUrl = [NSString stringWithFormat:#"%#%#", BASE_URL, requestUrl];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:completeRequestUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *results = [NSString stringWithFormat:#"%#", responseObject];
if (completion)
completion(results);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSString *results = [NSString stringWithFormat:#"Error"];
if (completion)
completion(results);
}];
}
You would then call your method like so:
[YourClass getRequestFromUrl:#"http://www.example.com" withCompletion:^(NSString *results){
NSLog(#"Results: %#", results);
}
AFNetworking's sample project has an example of using a block parameter to return a value from your web service calls: https://github.com/AFNetworking/AFNetworking/blob/master/Example/Classes/Models/Post.m
- (void)POST:(NSString *)URLString
parameters:(id)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
[_manager POST:[NSString stringWithFormat:#"%#%#",API_HOST,URLString] parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
block(formData);
} progress:^(NSProgress * _Nonnull uploadProgress1) {
uploadProgress(uploadProgress1);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
success(task,responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(task,error);
}];
}