I recently have asked about nil value from AFNetwirking GET query. Here is the question
I've got an answer
+ (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);
}];
}
[YourClass getRequestFromUrl:@"http://www.example.com" withCompletion:^(NSString *results){
NSLog(@"Results: %@", results);
}
Now I have another question: in MyClass I've got a method called getAllPlaces.
+ (void) getAllPlaces {
NSString * placesUrl = [NSString stringWithFormat: @"/url"];
NSMutableArray *places = [[NSMutableArray alloc] init];
[RestfulActions getRequestFromUrl:cafesUrl withCompletion:^(id placesInJSONFormat) {
NSArray *results = placesInJSONFormat;
for (NSDictionary *tempPlaceDictionary in results) {
Place *place = [[Place alloc] init];
for (NSString *key in tempPlaceDictionary) {
if ([place respondsToSelector:NSSelectorFromString(key)]) {
[place setValue:[tempPlaceDictionary valueForKey:key] forKey:key];
}
}
[places addObject:place];
}
}];
It works, but I want to return non-void value (NSArray places). And now it raises question about async tasks again. What should I do?
I want to access from another class with NSArray *places = [MyClass getAllPlaces]
I hope to get a correct answer. Thx, Artem.
You can't return an value from that block, as it's asynchronous and continues to run while other tasks are going on.
The correct way to handle this is to call the method that deals with this data from within the block and pass it the array.
You should try to implement the method like this:
And use it like this:
The success block will have the returned value if any!
Anything more? :)