AFNetworking Return value from async task iOS

2019-05-27 03:21发布

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.

2条回答
疯言疯语
2楼-- · 2019-05-27 03:46

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.

查看更多
等我变得足够好
3楼-- · 2019-05-27 04:06

You should try to implement the method like this:

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

And use it like this:

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

The success block will have the returned value if any!

Anything more? :)

查看更多
登录 后发表回答