【问题标题】:Download a file when an URL is given - iPhone sdk给出 URL 时下载文件 - iPhone sdk
【发布时间】:2011-09-21 22:48:02
【问题描述】:

如果给出 URL,是否可以从 Internet 下载文件并将其存储在文档目录中?我浏览了苹果开发者网站上的一些文件。它说它可以使用 NSURLDownload,但它不能在 iOS 中使用。因此,只有在 iOS 的情况下才应该使用 NSURLConnection 来完成。所以,有人帮我从给定的 URL 下载文件(甚至是 HTML 页面)。提前致谢。

【问题讨论】:

    标签: iphone ios4 download nsurlconnection nsurl


    【解决方案1】:

    我认为ASIHTTPRequest 库会帮助你:)

    ASIWebPageRequest

    ASIHTTPRequest 中包含的 ASIWebPageRequest 类可让您下载完整的网页,包括图像和样式表等外部资源。

    来自allseeing-i.com的代码示例

    - (IBAction)loadURL:(NSURL *)url
    {
       // Assume request is a property of our controller
       // First, we'll cancel any in-progress page load
       [[self request] setDelegate:nil];
       [[self request] cancel];
    
       [self setRequest:[ASIWebPageRequest requestWithURL:url]];
       [[self request] setDelegate:self];
       [[self request] setDidFailSelector:@selector(webPageFetchFailed:)];
       [[self request] setDidFinishSelector:@selector(webPageFetchSucceeded:)];
    
       // Tell the request to embed external resources directly in the page
       [[self request] setUrlReplacementMode:ASIReplaceExternalResourcesWithData];
    
       // It is strongly recommended you use a download cache with ASIWebPageRequest
       // When using a cache, external resources are automatically stored in the cache
       // and can be pulled from the cache on subsequent page loads
       [[self request] setDownloadCache:[ASIDownloadCache sharedCache]];
    
       // Ask the download cache for a place to store the cached data
       // This is the most efficient way for an ASIWebPageRequest to store a web page
       [[self request] setDownloadDestinationPath:
          [[ASIDownloadCache sharedCache] pathToStoreCachedResponseDataForRequest:[self request]]];
    
       [[self request] startAsynchronous];
    }
    
    - (void)webPageFetchFailed:(ASIHTTPRequest *)theRequest
    {
       // Obviously you should handle the error properly...
       NSLog(@"%@",[theRequest error]);
    }
    
    - (void)webPageFetchSucceeded:(ASIHTTPRequest *)theRequest
    {
       NSString *response = [NSString stringWithContentsOfFile:
          [theRequest downloadDestinationPath] encoding:[theRequest responseEncoding] error:nil];
       // Note we're setting the baseURL to the url of the page we downloaded. This is important!
       [webView loadHTMLString:response baseURL:[request url]];
    }
    

    【讨论】:

    • 这用于下载整个网页。最初的问题是要求下载“文件”。是否可以使用此库下载任意文件?
    • 好吧,我理解错了,但是库也可以下载任何大小的普通文件。
    • 知道这个库的存在很有趣。将来可能有用!感谢您的信息。
    【解决方案2】:

    这是一个从服务器获取图像并将其保存到文件的示例。

    创建实例变量

    NSMutableData *activeDownload;
    NSURLConnection *imageConnection;
    

    现在创建您的连接

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    NSURL *url = [[NSURL alloc] initWithString:@"URL TO FILE"];
    [request setURL:url];
    [url release];
    url = nil;
    
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    

    处理接收数据

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
        [self.activeDownload appendData:data];
    }
    

    传输完成,保存数据

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *fileName = [[paths objectAtIndex:0] stringByAppendingPathComponent:self.imageFileName];
    
    [self.activeDownload writeToFile:fileName atomically:YES];
    
    self.activeDownload = nil;
    self.imageConnection = nil;
    }
    

    还有一些我没有展示的代码(属性等),但我认为这应该可以为您提供足够的帮助。

    【讨论】:

    • 我使用了这段代码,它工作正常,但我认为有几件事要说,或者经验较少的人无法使其工作:1) NSURLConnection *conn 更好将其设为实例变量,否则 Xcode 将在未使用该变量时发出警报... 2) 启动下载时,您还需要初始化 activeDownload 变量 (self.activeDownload = [[NSMutableData alloc] init];)否则它不会保存任何东西。
    【解决方案3】:

    是的,您可以使用 NSURLConnection 来实现。您需要向 URL 发出请求。像这样的东西。

    NSString *strDownloadURL = @"File URL";
    NSMutableURLRequest *request  = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:strDownloadURL]];
    
    Connection *con = [[[Connection alloc] init];
    con.delegate=self;
    [[[NSURLConnection alloc]initWithRequest:request delegate:con] autorelease];
    

    现在,在 Connection Delegate Method didReceiveData 中将 NSData 分配给全局变量。

    - (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data {
      if (receivedData != nil) {
        [receivedData appendData:data];
      } else {
        receivedData = [[NSMutableData alloc] initWithData:data];
      }
    }
    

    最后,在连接委托方法“connectionDidFinishLoading”中,您应该拥有 NSData 格式的文件数据。所以将它存储在类似这样的文档目录中。

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
      [receivedData writeToFile:DocumentPathtoSaveFile atomically:YES];
    }
    

    【讨论】:

    • 抱歉,我创建了 Connection Custom 类供我个人使用。你可以替换"Connection *con = [[[Connection alloc] init]; con.delegate=self; [[[NSURLConnection alloc]initWithRequest:request delegate:con] autorelease];"到这个“NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];”
    猜你喜欢
    • 2011-04-29
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    • 2012-04-27
    相关资源
    最近更新 更多