AFNetworking Return value from iOS async task

I recently asked about the null value from an AFNetwirking GET request. Here is the question

I have 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 have 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 a non-empty value (NSArray places). And now he again raises the question of asynchronous tasks. What should I do? I want to access from another class using NSArray *places = [MyClass getAllPlaces] I hope to get the correct answer. Thanks, Artem.

+2
source share
2 answers

You should try to implement the method as follows:

 + (void) getTimeline:(NSString*)val success:(void (^)(id))success failure:(void (^)(NSError *))failure; 

And use it as follows:

 [MyClass getTimeline:nil success:^(id result) {} failure:^(NSError *error) {} 

The success block will have a return value, if any!

Anything else?:)

0
source

You cannot return a value from this block, since it is asynchronous and continues to be executed while other tasks are being performed.

The right way to handle this is to call a method that processes this data from the block and pass an array to it.

+1
source

Source: https://habr.com/ru/post/1215676/


All Articles