Capture Upload Image Failed iOS - 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 :(

Related

objective-c,How to send file as a parameter

I want to upload my image from my phone gallery to the server so I am not able to upload my program ,it runs successfully and shows print -
NSLog(#">>>>>>>>>> enter in ");
but it could not upload image on the server ,when I checked it in the app then there is no image ,and I also checked parameter, I think I am not sending proper file format in the parameter.
Please can anyone help me with proper file formate how to convert it
`
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)img
editingInfo:(NSDictionary *)editingInfo
{
[picker dismissModalViewControllerAnimated:YES];
NSURL *imagePath = [editingInfo objectForKey:#"UIImagePickerControllerReferenceURL"];
imageName = [imagePath lastPathComponent];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
localFilePath = [documentsDirectory stringByAppendingPathComponent:imageName];
NSLog(#"localFilePath.%#",localFilePath);
}
- (IBAction)submitBtn:(id)sender
{
NSURL* url;
url = [NSURL URLWithString:UrlBasic];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:url];
manager.requestSerializer = [AFJSONRequestSerializer serializerWithWritingOptions:NSJSONWritingPrettyPrinted];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
fileURL = [NSURL fileURLWithPath:localFilePath];
reqData=[[NSMutableDictionary alloc]initWithObjectsAndKeys:imageName1,#"image",#"addclassphotoactmobs",#"droot",schoolFolderA,#"schoolfolder",_choseGalleryTextF.text,#"gname",dividNum,#"classid",fileURL,#"uploadedfile",nil];
NSLog(#"reqData=%#",reqData);
[manager POST:UrlBasic parameters:reqData constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { }
progress:nil
success:^(NSURLSessionTask *task, NSMutableDictionary *responseObject) {
NSLog(#" %#",responseObject);
NSLog(#">>>>>>>>>> enter in ");
[self.view makeToast:#"submitted ....."
duration:3.0
position:CSToastPositionCenter];
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"error-=%#",error);
// [self.view makeToast:#"Please check internet connection !"];
}];
}
[Updated with imageNameStr]
While uploading your image data, it is necessary to send Name of the file.To generate a file Name, Here I've used Date and time.
Add the Code below the Line NSLog(#"reqData=%#",reqData);
====================
You have missed the formData Code.
Where as the image is the actual image in the below code.
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"yyyyMMddhhmmssSSS"];
NSString *imageNameStr = [NSString stringWithFormat:#"%#.jpg",[formatter stringFromDate:[NSDate date]]];
[sessionManager POST:appendURL
parameters:postParamDict
constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
if(image!=nil){
NSData * imageData = UIImageJPEGRepresentation(image,0.5f);
if(imageData!=nil){
[formData appendPartWithFileData:imageData
name:#"image"
fileName:imageNameStr
mimeType:#"image/jpg"];
}
}
}
progress:^(NSProgress * _Nonnull uploadProgress) {
}
success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
NSLog(#"%#",responseObject);
if(success)
success (responseObject);
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"error %#",error);
if(failure)
failure (error);
}]

upload video using AFNetworking without Block UI

I need to upload image without showing user some progress indicator. So basically like when you upload image in twitter/instagram when you do the submit, the upload view disappear instantly and you back to main ui.
Currently I'm using AFNetworking to upload the content and it success. Been searching for the solutions but can't find anywhere.
This is my current code for uploading the image to my server.
- (void)sendImage {
HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
HUD.dimBackground = NO;
[HUD setLabelText:#"Uploading"];
NSString *url = [NSString stringWithFormat:#"%#%#",kBaseURL,#"api/v1/media"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSData *imageData = UIImageJPEGRepresentation(uploadImage, 1);
NSString *base64PhotoString = [imageData base64EncodedStringWithOptions:0];
NSDictionary *parameters = #{#"caption": textfield.text,
#"photo_data":base64PhotoString};
__weak typeof(self) weakSelf = self;
[manager POST:url
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
[weakSelf successBlockFrDictionary:responseObject];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[HUD hide:YES];
[weakSelf showErrorMessageForError:error];
}];
}

How to upload the image/photo to a server using AFNetworking?

I am trying to upload the image/video to a webserver for iOS.
The uploading part of this server works fine. I checked it with Android version and I have already implemented the uploading method in Android app.
So I have found some codes for iOS on the stackoverflow.com
First, I am using the following code for uploading image.
But I can't upload at all and get the following result. I am using XCode6.1 on iOS8 SDK.
Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo=0x7fe24348d0b0 {NSUnderlyingError=0x7fe2434be120 "The request timed out.", NSErrorFailingURLStringKey=ServerURL, NSErrorFailingURLKey=ServerURL, NSLocalizedDescription=The request timed out.}
Here are the codes that I am using.
NSString* serverURL = #"http://www.myserver.com/file/postMedia.php";
UIImage *image = [UIImage imageNamed:#"sample.png"];
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
NSDictionary *param = #{#"userID":#"master",
[manager POST:serverURL parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"uploadedfile_thumb" fileName:#"photo.jpg" mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
....
});
return;
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
....
});
Certainly, the server works fine.
I have definitely tested with Android code.
So I'd like to know the exact code for iOS.
Thank you
This is my working code uploading an image to the server using AFNetworking:
+ (void)uploadImage:(UIImage *)image
ForUser:(WECUser *)user
withSuccessBlock:(void (^)(NSDictionary *response))resultBlock
faliureBlock:(void (^)(NSError *error))faliureBlock {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"yyyyMMddHHmmss";
NSString *dateString = [formatter stringFromDate:[NSDate date]];
NSString *fileName =
[NSString stringWithFormat:#"user_image_%#.jpg", dateString];
NSDictionary *dictionary = #{
#"user_id" : user._id,
#"resource_id" : user._id,
#"functioncode" : #"2000",
#"app_id" : [WECURLGenerator stringOfAppID],
#"file_name" : fileName
};
NSURLRequest *request = [[AFHTTPRequestSerializer serializer]
multipartFormRequestWithMethod:
#"POST" URLString:[WECURLGenerator stringOfImageUploadingBaseURL]
parameters:dictionary
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData
appendPartWithFileData:UIImageJPEGRepresentation(image, 0.6)
name:#"file1"
fileName:fileName
mimeType:#"jpg"];
} error:(NULL)];
AFHTTPRequestOperation *operation =
[[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation,
id responseObject) {
NSDictionary *resultDict =
[NSJSONSerialization JSONObjectWithData:responseObject
options:NSJSONReadingMutableLeaves
error:nil];
resultBlock(resultDict[#"record"]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
faliureBlock(error);
}];
[operation start];
}
Hope this helps.
Your code looks fine, I am using same code for uploading an image using AFNetworking. But you haven't mentioned how you are picking the image. Because you can not upload an image directly like:
UIImage *image = [UIImage imageNamed:#"sample.png"];
Are you using UIImagepickerController for picking your image?
If YES than see my code;
-(IBAction)chooseImg:(id)sender{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
picker = [[UIImagePickerController alloc]init];
picker.allowsEditing = NO;
picker.delegate = self;
picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType: UIImagePickerControllerSourceTypeCamera];
[self.navigationController presentViewController:picker animated:YES completion:nil];
}
else{
picker = [[UIImagePickerController alloc]init];
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
picker.allowsEditing = YES;
picker.delegate = self;
picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self.navigationController presentViewController:picker animated:YES completion:nil];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
NSURL *name = [info objectForKey:UIImagePickerControllerReferenceURL];
image = [info objectForKey:UIImagePickerControllerOriginalImage];
ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset *imageAsset){
ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
NSDictionary *metadata = imageAsset.defaultRepresentation.metadata;
NSLog(#"Meta:%#",metadata);
NSString *str = [imageRep filename];
txtImg.text = str;
};
ALAssetsLibrary *assetLib = [[ALAssetsLibrary alloc]init];
[assetLib assetForURL:name resultBlock:resultBlock failureBlock:nil];
[self.navigationController dismissViewControllerAnimated:YES completion:nil];
}
NOTE: Here I used metadata to display name of the image,it's not necessary you can skip this.
Than in uploading part:
NSString* serverURL = #"http://www.myserver.com/file/postMedia.php";
//UIImage *image = [UIImage imageNamed:#"sample.png"];
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
NSDictionary *param = #{#"userID":#"master",
[manager POST:serverURL parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"uploadedfile_thumb" fileName:#"photo.jpg" mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
....
});
return;
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
....
});
This works for me uploading an image.
Hope it works for you.

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];

handling the Response with the AFNetworking 2

i am really new to IOS development. i want to develop an application which is dealing with some web services and display in a table view. somehow i found a 3rd party library for do the networking stuffs [AFNetworking 2]. below is my code to get the json response for any given url and parameters.
-(NSDictionary*)getWebServiceResponce:(NSString *)url :(NSDictionary *)object
{
// NSDictionary *parameters = [[NSDictionary alloc] initWithObjectsAndKeys:#"47", #"caregiverPersonId", nil];
__block NSDictionary* result=Nil;
__block NSString* person=Nil;
AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
[policy setAllowInvalidCertificates:YES];
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
[operationManager setSecurityPolicy:policy];
operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
operationManager.responseSerializer = [AFJSONResponseSerializer serializer];
[operationManager POST:url
parameters:object
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", [responseObject description]);
person = [responseObject[#"d"]objectForKey:#"PersonId"];
// [self returnedResponce:responseObject];
result = (NSDictionary *) responseObject[#"d"];
NSLog(#"RESULT: %#", result);
NSLog(#"personm: %#", person);
[operation waitUntilFinished];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error description]);
//result = [error];
}
];
return result;
}
this code works perfectly.. but my point is when i put some breakpoints to check what are the values i got for several variables, it shows null. but my log shows the entire json response.
and i want to return my response object as a dictionary. because i want to do some process with the response.. can some one help me with this ?
The problem is that result is nil when it gets returned. AFNetworking uses ObjC's awesome blocks, they get executed asynchronously. Read more about it here.
You should include a callback block in your getWebServiceResponce method. I've thrown together a bit of code but you should really read more about blocks.
-(void)webServiceResponceForURL:(NSString *)url dictionary:(NSDictionary *)object success:(void (^)(NSDictionary *responseObject))success {
// NSDictionary *parameters = [[NSDictionary alloc] initWithObjectsAndKeys:#"47", #"caregiverPersonId", nil];
__block NSDictionary* result=Nil;
__block NSString* person=Nil;
AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
[policy setAllowInvalidCertificates:YES];
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
[operationManager setSecurityPolicy:policy];
operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
operationManager.responseSerializer = [AFJSONResponseSerializer serializer];
[operationManager POST:url
parameters:object
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", [responseObject description]);
person = [responseObject[#"d"]objectForKey:#"PersonId"];
// [self returnedResponce:responseObject];
result = (NSDictionary *) responseObject[#"d"];
NSLog(#"RESULT: %#", result);
NSLog(#"personm: %#", person);
//We are executing the block as soon as we have the results.
if (success) {
success(responseObject);
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error description]);
//result = [error];
}
];
}
Edit:
[self webServiceResponceForURL:#"foo://foo" dictionary:nil success:^(NSDictionary *responseObject) {
//your code here
}
[self webServiceResponceForURL:#"foo://foo" dictionary:nil success:^(NSDictionary *responseObject) {
//your code here
}
Here you will got complete responseObject in form NSDictionary. You can assign responseObject to instance variable. Now This instance Variable will be used at point time. in your case, it will passed on button event.

Resources