AFHTTPRequestOperationManager return data in block

2019-03-05 10:37发布

问题:

I created an APIController in my application that has several methods that call specific api urls and return a model object populated with the result of the api call.

The api works with json and up to now my code looks like the following:

//Definition:
- (MyModel *)callXYZ;
- (MyModel *)callABC;
- (MyModel *)call123;

//Implementation of one:
- (MyModel *)callXYZ {

    //Build url and call with [NSData dataWithContentsOfURL: url];
    //Create model and assign data returned by api

    return model;

}

Now I want to use the great AFNetworking framework to get rid of that "dataWithContentsOfURL" calls. So I changed my methods:

- (MyModel *)callXYZ {
    __block MyModel *m;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //process data and assign to model m
    }
    return m;
}

This code won't work cause the empty model gets returned before the url call has finished. I am stuck and don't know how to refactor my design to get this to work.

//EDIT: I don't know if it is important to know, but I later want to show a loading animation while the api gets called.

回答1:

- (void)callXYZWithCompletion:(void (^)(MyModel *model))completion {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        MyModel *m;
        //process data and assign to model m

        if(completion) {
            completion(m);
        }
    }
}

Usage example:

// Start the animation

[self callXYZWithCompletion:^(MyModel *model) {
    // Stop the animation
    // and use returned model here
}];