AFHTTPRequestOperationManager return data in block

安稳与你 提交于 2019-12-31 07:15:44

问题


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


来源:https://stackoverflow.com/questions/22580996/afhttprequestoperationmanager-return-data-in-block

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