我在异步进行ftp请求时遇到了一个问题,我尝试清楚地描述确切的问题:
- (void)viewDidLoad
{
[super viewDidLoad];
//I want to do a ftpListRequst in the background here
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NewFTPListService *nfl = [[NewFTPListService alloc] initWithFtpPath:@"ftp://root:@10.0.0.3/"];
[nfl listDirectoryContents];
[nfl release];
});
//other main thread code
}
- (NSArray *) listDirectoryContents
{
[_listDir start];
//What I want to do here is to wait until the ftp request finish
while (!self.isFinish) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
NSLog(@"Request Finish!");
return self.result;
}
-(void) start {
......
self.streamInfo->readStream.delegate = self;
[self.streamInfo->readStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.streamInfo->readStream open];
//If request is blocked (may be the server is not avaliable), after a specific time, this block will be called
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, kWRDefaultTimeout * NSEC_PER_SEC), dispatch_get_current_queue(), ^{
[self.delegate requestFailed:self];
[self destroy];
});
}
当请求成功时,会调用这个方法:
-(void) requestCompleted:(WRRequest *) request{
self.isSucess = YES;
self.isFinish = YES;
}
此方法将在“dispatch_after”块中调用
-(void) requestFailed:(WRRequest *) request{
self.isSucess = NO;
self.isFinish = YES;
}
当请求成功时,我看到打印“请求完成!”。当请求被阻止并调用“dispatch_after”块时,会调用“requestFailed”方法,但我没有看到打印“请求完成!”。似乎程序以某种方式卡在了while循环中(循环没有运行,之后的代码也没有运行)。
更重要的是,如果我同步运行程序:
- (void)viewDidLoad
{
[super viewDidLoad];
NewFTPListService *nfl = [[NewFTPListService alloc] initWithFtpPath:@"ftp://root:@10.0.0.3/"];
[nfl listDirectoryContents];
[nfl release];
}
即使请求失败,我也可以成功看到打印“请求完成!”。我想知道为什么会发生这种情况以及如何解决这个问题,以便在请求失败时可以成功运行程序。谢谢!