AFNetworking Return value from async task iOS

南楼画角 提交于 2020-01-02 18:17:55

问题


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.


回答1:


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? :)




回答2:


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.



来源:https://stackoverflow.com/questions/20070571/afnetworking-return-value-from-async-task-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!