AFNetworking从异步任务iOS返回值 [英] AFNetworking Return value from async task iOS

查看:478
本文介绍了AFNetworking从异步任务iOS返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近从AFNetwirking GET查询中询问了零值. 这是问题

I recently have asked about nil value from AFNetwirking GET query. Here is the question

我有一个答案

+ (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);
}

现在我还有另一个问题:在MyClass中,我有一个名为getAllPlaces的方法.

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

}];

它可以工作,但是我想返回非空值(NSArray位置).现在,它又引发了有关异步任务的问题.我该怎么办? 我想使用NSArray *places = [MyClass getAllPlaces]从另一个类访问 我希望得到一个正确的答案. Thx,Artem.

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.

推荐答案

您应尝试实现以下方法:

You should try to implement the method like this:

+ (void) getTimeline:(NSString*)val success:(void (^)(id))success failure:(void (^)(NSError *))failure;

并像这样使用它:

[MyClass getTimeline:nil
               success:^(id result) {} failure:^(NSError *error) {} 

成功块将具有返回值(如果有)!

The success block will have the returned value if any!

还有什么? :)

这篇关于AFNetworking从异步任务iOS返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆