0

ASIHTTPRequest用来检查用户是否登录,并在登录成功时尝试返回一个布尔值

问题:当我请求布尔值时,它总是返回 0,然后几秒钟后 ASIHTTPRequest完成它的请求并更新布尔值。

我想要的:在所有请求完成后获取布尔值。我认为正确的方法是编写一个布尔函数并检索 asihhtp 请求的结果?

在单例中:

@interface CloudConnection : NSObject
{
    BOOL isUserLoggedIN;
}
@property BOOL isUserLoggedIN;
+ (CloudConnection  *)sharedInstance;
@end

+ (CloudConnection *)sharedInstance
{
    static CloudConnection *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[CloudConnection alloc] init];
        // Do any other initialisation stuff here

    });
    return sharedInstance;
}

- (id)init {
    if (self = [super init]) {
        //send login request
        [self sendLoginRequest];
    }
    return self;
}
-(void) sendLoginRequest{ .....}
- (void)requestFinished:(ASIHTTPRequest *)request
{ else if (request.responseStatusCode == 202) {
        //parse  json data
        NSLog(@"Login Succesfull");
        _isUserLoggedIN=YES;
    }
}
- (void)requestFailed:(ASIHTTPRequest *)request{}

在 VC 中:

CloudConnection *sharedInstance=[CloudConnection  sharedInstance];
 NSLog(@"is logged in init %hhd",sharedInstance.isUserLoggedIN);
[self performSelector:@selector( checkLoginAfterFiveSeconds) withObject:nil afterDelay:5.0];

-(void) checkLoginAfterFiveSeconds
{

    CloudConnection *sharedInstance=[CloudConnection  sharedInstance];
    NSLog(@"is logged in init %hhd",sharedInstance.isUserLoggedIN);
}

NSLOG:

is logged in init 0
Login Succesfull`
is logged in init 1 //after 5 secs
4

2 回答 2

0

好吧,如果你按照你的建议去做,它会阻塞调用线程。而且您永远不希望线程等待网络流量,尤其是主/ ui线程

将其设为 void 函数并调用completionHandler 或...一旦可以直接计算结果,就发送一个NSNotification!:)

于 2013-03-04T18:12:06.263 回答
0

是的,您是对的 :) 在您的请求完成块中调用此方法:

[self loginResult:result];

-(void)loginResult:(BOOL)result
{
    if(result == TRUE)
    {
        NSLog(@"Login successfully now call any method or do what ever you want");
    }
    else
    {
        NSLog(@"Login unsuccessfull");
    }
}
于 2013-03-10T10:50:40.423 回答