【问题标题】:downloading web page using NSURLDownload使用 NSURLDownload 下载网页
【发布时间】:2011-11-30 04:39:25
【问题描述】:

这是我的代码,它尝试使用 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!");
    }

}

【问题讨论】:

  • 有什么不好的?它是否打印download has failed!?您是否实现了任何NSURLDownloadDelegate 方法,例如downloadDidFinish:download:didFailWithError:
  • 它没有给我任何错误!我已经实现了代表,但它们似乎不起作用!我不知道是什么问题。

标签: objective-c download


【解决方案1】:

确保实现 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:委托: 返回 URL 请求的初始化 URL 下载并开始下载该请求的数据。

- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate

委托

下载的委托。该对象将接收委托 下载过程中的消息。代表消息将在 调用此方法的线程。为了使下载正常工作 调用线程的运行循环必须在默认运行中运行 循环模式。

NSURLConnection 有同步下载数据的方式。

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#//apple_ref/doc/uid/20001836-BAJEAIEE

NSURLConnection 支持下载 NSURLRequest 以同步方式使用类方法 发送同步请求:返回响应:错误:。使用这种方法是 不推荐,因为它有严重的限制:

主要限制是客户端块,但这是命令行应用程序中的一个问题。

【讨论】:

  • 我的程序是命令行的,为什么不能下载?因为它不是 GUI 程序,所以不能使用委托!
  • 命令行无关紧要 - 创建一个执行 main.m 调用的工作(下载)的类。该类需要实现那些委托回调。
  • 这就是我所做的,但由于它不起作用,我在论坛上问过它,他们说代表只在 GUI 程序中工作,而不是在命令行程序中工作。在我上面的代码下面的类中,我已经实现了代表。但他们不工作!
  • hmmm - 委托只是一个符合协议的回调。也许我缺少一些东西。我会试一试,然后回来查看。
【解决方案2】:

您需要确保至少定义了downloadDidFinish:download:didFailWithError: 使用委托。您几乎可以从URL Loading System Programming Guide 复制和粘贴方法。

如果您使用的是 10.7,您应该在标头中声明您也使用该协议,在 Lion 之前没有正式的协议。

还要确保你有一个运行循环。对于测试,您可以将[[NSRunLoop currentRunLoop] run]; 粘贴在那里,尽管它可能永远不会退出循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    • 2018-01-15
    • 2014-04-15
    • 2017-06-28
    相关资源
    最近更新 更多