iosobjective-creturn-valueafnetworking-3

How to return value in completion block


I have class that manages connections with AFNetworking.

So I want to call my function like NSDictionary *dict = [ServerManager requestWithURL:@"https://someurl.com"];

And that's the function in the other class:

- (NSDictionary *) requestWithURL:(NSString *)requestURL {
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
    [manager GET:requestURL parameters:nil progress:nil
         success:^(NSURLSessionDataTask *operation, id responseObject){

             return responseObject;

    }
         failure:^(NSURLSessionDataTask *operation, NSError *error) {

    }];
}

I know that is incorrect to do that. So what should I do to return responseObject back to NSDictionary *dict? I'd like to get the basic idea of asynchronous development with blocks.


Solution

  • Since the networking request completes long after its is launched, the only way to handle the result is with a block passed to your request method...

    // when request completes, invoke the passed block with the result or an error
    - (void)requestWithURL:(NSString *)requestURL completion:(void (^)(NSDictionary *, NSError *))completion {
        AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
        [manager GET:requestURL parameters:nil progress:nil success:^(NSURLSessionDataTask *operation, id responseObject){
            if (completion) completion((NSDictionary*)responseObject, nil);
        }, failure:^(NSURLSessionDataTask *operation, NSError *error) {
            if (completion) completion(nil, error);
        }];
    }
    

    Make it public in a ServerManager.h

    - (void)requestWithURL:(NSString *)requestURL completion:(void (^)(NSDictionary *, NSError *))completion;
    

    Elsewhere, call it:

    [ServerManager requestWithURL:@"http://someurl.com" completion:^(NSDictionary *dictionary, NSError *error) {
        // check error and use dictionary
    }];