可以等待完成等待?

时间:2014-04-09 18:25:52

标签: ios afnetworking blocking

是否可以等待某个服务器查询块结束其操作?我的工作代码如下;

 + (BOOL) loginQueryFromServer:(NSDictionary *)parameters{

  __block BOOL loginQueryResult = NO;

  AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

  AFHTTPRequestOperation *operation = [manager POST:@"http://domainname/login/" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {

    NSLog(@"Response1: %@",responseObject);
    loginQueryResult = YES;
    NSLog(@"Response2: %@", loginQueryResult ? @"YES" : @"NO");
  } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    NSLog(@"Error: %@", error);
    loginQueryResult = NO;
  }];
  [operation start];
  [operation waitUntilFinished];

  NSLog(@"Response3: %@", loginQueryResult ? @"YES" : @"NO");
  return loginQueryResult;
}

结果:(如您所见; Response3首先记录)

2014-04-09 21:11:17.072 aaa[1010:70b] Response3: NO
2014-04-09 21:11:17.073 aaa[1010:70b] Response1: {
    reply = "Login successful!";
}
2014-04-09 21:11:17.081 aaa[1010:70b] Response2: YES

2 个答案:

答案 0 :(得分:2)

我知道这并没有完全回答这个问题 - 但我建议你重写你的loginQueryFromServer:方法来接受一个完成块本身,以便它是异步的(我认为这最终是你想要做的): / p>

+ (void) loginQueryFromServer:(NSDictionary *)parameters completion:(void(^)(BOOL response, NSError *error))completionBlock {

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    AFHTTPRequestOperation *operation = [manager POST:@"http://domainname/login/" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {

        completionBlock(YES, nil);

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

        completionBlock(NO, error);
    }];
    [operation start];
} 

像这样使用:

[YourClass loginQueryFromServer:someDictionary completion:^(BOOL response, NSError *error) {

    // do something with the response and the error if it exists
}];

答案 1 :(得分:1)

您正在使用第三方AFNetworking库。所以问题是:那些开发人员希望你能在操作完成后做些什么吗?

答案是yes

  

NSOperation提供的内置completionBlock允许在请求完成后执行自定义行为。

您正在使用的课程是NSOperation的子类。因此,为其completionBlock property分配一个块。