Code inside for in loop not being executed - ios

I have the following method, I've verified that the for in loop runs, however the code inside it doesn't. I really can't explain myself this behaviour.
- (void) getReviews:(NSString *)packageID withCompletionHandler:(ResponseBlock)completionBlock {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSDictionary* parameters = #{#"packageID" : packageID};
[manager GET:(#"theurl") parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSTEasyJSON* JSON = [NSTEasyJSON withObject:responseObject];
NSString *jsonString = JSON.string;
if ([jsonString containsString:#"Could"]) {
completionBlock(jsonString);
} else {
for (NSTEasyJSON *arrayItemJSON in JSON.dictionary) {
NSString* rte = arrayItemJSON[#"rate"].string;
NSString* ttl = arrayItemJSON[#"title"].string;
NSString* rvw = arrayItemJSON[#"review"].string;
NSString* uname = arrayItemJSON[#"username"].string;
NSLog(#"This is the rate %#", rte);
}
}
completionBlock(jsonString);
} failure:^(NSURLSessionTask *operation, NSError *error) {
completionBlock(#"Error ocurred");
}];
}

Related

AFHTTPRequestOperationManager isn't call (no response/no faillure)

Here's my code :
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
mainManager = [AFHTTPRequestOperationManager manager];
mainManager.requestSerializer.timeoutInterval = 30;
I initialise my AFHTTPRequestOperationManager like this.
urlToWhere = #"myurl.php";
parameters = #{#"user_id": "1"};
NSLog(#"a");
[mainManager POST:urlToWhere parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"result");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error");
}];
NSLog(#"b");
The fact is my a is display in the logs, but none of "result" or "error" are displayed, and then the b is displayed.
Is there any exception where the AFHTTPRequestOperationManager would be dodge ?
I can not comment at the moment, so using the answer options. shouldn't your urlToWhere parameter like this
urlToWhere = #"http://myurl.php";

How would I send a PUT request with the following information using AFNetWorking?

This is what my server API document shows me to return a successful request.
curl -X PUT -d {"questions":[{"type":"control_head"}]} "https://api.request.com/forms"
{"questions":[{"type":"control_head"}]} this is the parameter.
https://api.request.com/forms this is the URL.
How can I handle this properly handle this using AFNetWorking? This is what I've got so far.
NSString *urlStr = [NSString stringWithFormat:#"https://api.request.com/forms"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager PUT:urlStr parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
[operation setUserInfo:userinfo];
SBJsonParser *jsonparser = [SBJsonParser new];
id result = [jsonparser objectWithString:[operation responseString]];
if ( self.delegate != nil && [self.delegate respondsToSelector:finishSelector] ) {
[self.delegate performSelector:finishSelector withObject:result];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[operation setUserInfo:userinfo];
if ( self.delegate != nil && [self.delegate respondsToSelector:failSelector] ) {
[self.delegate performSelector:failSelector withObject:[operation error]];
}
}];
I am not sure how to handle parameter correctly.
You can construct an NSDictionary equivalent of your parameters with:
NSDictionary *parameters = #{#"questions": #[#{#"type": #"control_head"}]};
Just pass that into PUT, and it should work as expected.

POST with URL parameters and JSON body in AFNetworking

I'd like to make a POST call that has both URL parameters and a JSON body:
URL http://example.com/register?apikey=mykey
JSON { "field" : "value"}
How can I use two different serializers at the same time with AFNNetworking? Here's my code with the URL parameters missing:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:#"http://example.com/register" parameters:json success:^(AFHTTPRequestOperation *operation, id responseObject) {
I make a post method
/**
* Services gateway
* Method get response from server
* #parameter -> object: request josn object ,apiName: api endpoint
* #returm -> void
* #compilationHandler -> success: status of api, response: respose from server, error: error handling
*/
+ (void)getDataWithObject:(NSDictionary *)object onAPI:(NSString *)apiName withController:(UIViewController*)controller
:(void(^)(BOOL success,id response,NSError *error))compilationHandler {
controller = controller;
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
// set request type to json
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
// post request to server
[manager POST:apiName parameters:object success:^(AFHTTPRequestOperation *operation, id responseObject) {
// NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject
options:0
error:&error];
//NSString *JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
////
// check the status of API
NSDictionary *dict = responseObject;
NSString *statusOfApi = [[NSString alloc]initWithFormat:#"%#"
,[dict objectForKey:#"OK"]];
// IF Status is OK -> 1 so complete the handler
if ([statusOfApi isEqualToString:#"1"] ) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
compilationHandler(TRUE,responseObject,nil);
} else {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSArray *errorMessages = [responseObject objectForKey:#"messages"];
NSString *message = [errorMessages objectAtIndex:0];
[Utilities showAlertViewWithTitle:apiName message:message];
compilationHandler(FALSE,responseObject,nil);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSString *message = [NSString stringWithFormat:#"%#",[error localizedDescription]];
NSLog(#"Message is %#", message);
NSString *errorMessage = [NSString stringWithFormat:#"%#",[error localizedDescription]];
if (!([message rangeOfString:#"The request timed out."].location == NSNotFound)) {
[Utilities showAlertViewWithTitle:apiName message:errorMessage];
}
compilationHandler(FALSE,errorMessage,nil);
}];
// For internet reachibility check if changes its state
[self checkInternetReachibility:manager];
}
**for Example when we call the Service **
// calling service gateway API
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
"field",#"value",
nil];
[self getDataWithObject:dict onAPI:KGet_Preferences withController:(UIViewController*)controller :^(BOOL success, id response, NSError *error) {
if( success ) {
NSMutableDictionary *data = [[response valueForKey:#"data"] valueForKey:#"preferences"];
compilationHandler(success,data,error);
} else {
compilationHandler(success,nil,error);
}
}];
I believe there is no automatic way of doing it. However, there is a simple way of achieving it manually:
- (NSMutableURLRequest *)someRequestWithBaseURL:(NSString *)baseUrl
method:(NSString *)method
path:(NSString *)path
uriParameters:(NSDictionary *)uriParameters
bodyParameters:(NSDictionary *)bodyParameters
NSURL *url = [NSURL URLWithString:path relativeToURL:[NSURL URLWithString:baseUrl]];
AFHTTPRequestSerializer *httpRequestSerializer = [AFJSONRequestSerializer serializerWithWritingOptions:0]
NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithDictionary:bodyParameters];
if ([httpRequestSerializer.HTTPMethodsEncodingParametersInURI containsObject:method]) {
[parameters addEntriesFromDictionary:uriParameters];
} else {
NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:YES];
// For urlEncodedString, check http://stackoverflow.com/a/718480/856549
urlComponents.percentEncodedQuery = [uriParameters urlEncodedString];
url = [urlComponents URL];
}
NSError *error;
NSURLRequest *request = [httpRequestSerializer requestWithMethod:method
URLString:[url absoluteString]
parameters:parameters
error:&error];

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.

AFNetworking 2.0 adds [] square brackets to json that get send to server

I am using AFNetworking 2.0 and have run into a problem.
I am trying to PUT an array in json to the server.
I am posting the Array like (See Code Below). I am adding the following array to the Json params to send to the server:
themes = (
"Fashion - Men",
Kids,
"Styling / Hair"
);
and this gets send to the server:
{
id = 654;
tags = test;
themes = (
"Fashion - Men",
Kids,
"Styling / Hair"
);
}
However the server receives the json like so WHICH IS WRONG:
{'id': '654', 'themes[]': ['Kids', 'Styling / Hair', 'Accessories - Women'], 'tags': 'test'}
AFNetworking is putting [] square brackets by themes in the sent json like themes[] so the cal is right except for this:themes[]
Have no idea how to fix this.
- (void) piccMedia: (NSString*) aPiccId Tags: (NSString *) aTags Themes: (NSMutableArray *) anThemes
success:(void (^)(NSArray *response))success
failure:(void (^)(NSError *error))failure
{
NSMutableDictionary * params = [[NSMutableDictionary alloc] init];
[params setObject: #"654" forKey:#"id"];
[params setObject: aTags forKey:#"tags"];
[params setObject: anThemes forKey:#"themes"];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *piccingAuthToken = [prefs stringForKey:#"piccingAuthToken"];
NSString *piccingUsername = [prefs stringForKey:#"piccingUsername"];
NSLog(#"piccingAuthToken %# %#", piccingAuthToken,piccingUsername);
NSString *postQueryString = [NSString stringWithFormat:#"http://dev.com/services/rest/profiles/%#/media",piccingUsername];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [JSONResponseSerializerWithData serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript", #"text/plain", #"text/html", nil];
manager.responseSerializer = [JSONResponseSerializerWithData serializerWithReadingOptions:NSJSONReadingAllowFragments | NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves];
[manager.requestSerializer setValue:piccingAuthToken forHTTPHeaderField:#"x-authtoken"];
[manager PUT:postQueryString parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
success(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
id json = error.userInfo [JSONResponseSerializerWithDataKey];
failure(json);
}];
}
2014-02-24 16:49:25.265 App[7314:70b] JSON Parameters{
id = 654;
tags = test;
themes = (
"Accessories - Women",
"Styling / Hair",
Kids
);
}
You should set requestSerializer to AFJSONRequestSerializer
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setRequestSerializer:[AFJSONRequestSerializer serializer]];
[manager POST:#"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

Resources