我是可可编程新手,我正在尝试从url下载二进制文件到磁盘。不幸的是,由于某些原因,这些方法没有被调用。对downloadFile的调用是由后台线程通过self performSelectorOnBackground等启动的。有什么想法我做错了什么?
注意:当我从主UI线程调用downloadFile时,它似乎正常工作,后台线程是怎么回事?
-(BOOL) downloadFile
{
BOOL downloadStarted = NO;
// Create the request.
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:versionLocation]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// Create the connection with the request and start loading the data.
NSURLDownload *theDownload = [[NSURLDownload alloc] initWithRequest:theRequest
delegate:self];
if (theDownload) {
// Set the destination file.
[theDownload setDestination:@"/tmp" allowOverwrite:YES];
downloadStarted = YES;
} else {
// inform the user that the download failed.
downloadStarted = NO;
}
return downloadStarted;
}
- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error
{
// Release the connection.
[download release];
// Inform the user.
NSLog(@"Download failed! Error - %@ %@",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)downloadDidFinish:(NSURLDownload *)download
{
// Release the connection.
[download release];
// Do something with the data.
NSLog(@"%@",@"downloadDidFinish");
}发布于 2013-07-15 05:33:25
我认为您应该启动连接NSURLDownload对象的run循环。默认情况下,它将使用当前线程的run循环,因此您可能应该在初始化NSURLDownload对象之后执行类似的操作:
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
while (!self.downloaded && !self.error && [runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]])
;属性self.downloaded和self.error应该在回调中设置。
在主线程中,运行循环可能是由NSApplication对象启动的。
https://stackoverflow.com/questions/17638644
复制相似问题