NSURLSession方法在登录时返回true或false

时间:2017-05-30 10:36:19

标签: ios nsurlconnection nsurlsession

我有这个调用Web服务的UIViewController。

为了对该Web服务进行任何调用,我需要先登录。 成功登录后,我收到了

  • 会话Cookie
  • 用户特定数据

我需要这些数据用于对服务器的任何后续调用。

因此,一个简单的方法是(伪代码):

if([self Login]){
    [self getSomeJsonDataForThisUser];
}

现在,问题在于,作为一个好公民,我正在远离NSURLConnection,并且NSURLSessions都是异步的。

基本问题是: 我怎么能写这样的方法:

-(BOOL)Login{
  --do some async stuff here
  --return TRUE or FALSE
)

谢谢!

1 个答案:

答案 0 :(得分:1)

由于异步行为,您需要一个带有完成处理程序的方法

- (void)loginWithCompletion: (void (^)(BOOL))completion {
    // do some async stuff here
    completion(true); // This line returns the result of the task.
}

并使用它

[self loginWithCompletion:^(BOOL result) {
    NSLog(@"result: %d", result);
    if (result) {
        [self getSomeJsonDataForThisUser];
    }
}];