这是我的代码,它尝试使用NSURLDownload下载网页。但是它不工作,它是一个命令行程序。
- (void)startDownloadingURL
{
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/index.html"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// Create the download with the request and start loading the data.
NSURLDownload *theDownload = [[NSURLDownload alloc] initWithRequest:theRequest delegate:self];
if (theDownload) {
// Set the destination file.
[theDownload setDestination:@"/saleh" allowOverwrite:YES];
} else {
// inform the user that the download failed.
NSLog(@"download has failed!");
}
}发布于 2011-11-15 12:27:56
确保您实现了downloadDidFinish和doanload:didFailWithError:回调。
下面是关于如何使用NSURLDownload的概述:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLDownload.html#//apple_ref/doc/uid/20001839-BAJEAIEE
具体地说,此回调将向您提供更多失败原因的详细信息:
- (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]);
}编辑:
下面你说这是一个命令行。异步回调需要NSRunLoop。请参见:
Cocoa: NSURLConnection not attempting an HTTP Request
根据文档:
initWithRequest:delegate:返回URL请求的初始化URL下载,并开始下载请求的数据。
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate委派
下载的委托。此对象将在下载过程中接收委托消息。委托消息将在调用此方法的线程上发送。为了使下载能够正常工作,调用线程的run循环必须在默认的run循环模式下运行。
NSURLConnection有一种同步下载数据的方式。
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#//apple_ref/doc/uid/20001836-BAJEAIEE
对于使用类方法sendSynchronousRequest:returningResponse:error:.以同步方式下载NSURLRequest内容,
NSURLConnection提供了支持不推荐使用此方法,因为它有严重的限制:
主要的限制是客户端块,但这是命令行应用程序中的一个问题。
发布于 2011-11-30 04:39:26
您需要确保至少定义了downloadDidFinish:和download:didFailWithError:才能使用委托。您可以很容易地从URL Loading System Programming Guide中复制和粘贴方法。
如果你在10.7上,你应该声明你在你的头中也使用了协议,在Lion之前没有正式的协议。
还要确保你有一个运行循环。对于测试,您可以只将[[NSRunLoop currentRunLoop] run];放在其中,尽管那时它可能永远不会退出循环。
https://stackoverflow.com/questions/8131441
复制相似问题