当我异步执行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];
}
即使请求失败,我也能成功看到打印"请求完成!"。我想知道为什么会发生这种情况以及如何解决这个问题,这样我就可以在请求失败时成功运行程序。谢谢!
答案 0 :(得分:0)
您好,只需通过performSelector
调用此方法[nfl listDirectoryContents];
或在viewDidAppear方法中调用此方法。