简体   繁体   中英

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.

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
}];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM