首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用NSURLDownload下载网页

使用NSURLDownload下载网页
EN

Stack Overflow用户
提问于 2011-11-15 12:18:08
回答 2查看 1.7K关注 0票数 0

这是我的代码,它尝试使用NSURLDownload下载网页。但是它不工作,它是一个命令行程序。

代码语言:javascript
复制
- (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!");
    }

}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 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

具体地说,此回调将向您提供更多失败原因的详细信息:

代码语言:javascript
复制
- (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下载,并开始下载请求的数据。

代码语言:javascript
复制
- (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提供了支持不推荐使用此方法,因为它有严重的限制:

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

票数 0
EN

Stack Overflow用户

发布于 2011-11-30 04:39:26

您需要确保至少定义了downloadDidFinish:download:didFailWithError:才能使用委托。您可以很容易地从URL Loading System Programming Guide中复制和粘贴方法。

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8131441

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档