给定 URL 时下载文件 - iPhone sdk

发布于 2024-11-17 09:07:40 字数 165 浏览 3 评论 0原文

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

Is it possible to download a file from internet store it in document directory when an URL is given? I went through some documents in apple developer's site. It said that its possible using NSURLDownload, but it cannot be used in iOS. So, it should be done by using NSURLConnection only in case of iOS. So, someone help me download a file(even the HTML page) from the given URL. Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

月下伊人醉 2024-11-24 09:07:40

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

创建您的实例变量

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;
}

还有我没有显示的代码的其他部分(属性等),但我认为这应该会给您足够的帮助。

Here's an example of getting an image from a server and saving it to a file.

Create your instance variables

NSMutableData *activeDownload;
NSURLConnection *imageConnection;

Now create your connection

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];

Handle receiving data

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

Transfer finished, save the 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;
}

There are other bits of the code I've not shown (properties, etc), but this should give you enough to help, I think.

离去的眼神 2024-11-24 09:07:40

我认为 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]];
}

I think the ASIHTTPRequest library will help you :)

ASIWebPageRequest

The ASIWebPageRequest class included with ASIHTTPRequest lets you download complete webpages, including external resources like images and stylesheets.

Code Example from 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]];
}
°如果伤别离去 2024-11-24 09:07:40

是的,您可以使用 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];

现在,在连接委托方法 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];
}

Yes You can do it with NSURLConnection. You need to make a request to URL. Something like this.

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];

Now, in Connection Delegate Method didReceiveData Assign NSData to Global Variable.

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

Finally, In Connection delegate Method "connectionDidFinishLoading" You should have your file data in NSData Format. So store it in Document directory something like this.

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
  [receivedData writeToFile:DocumentPathtoSaveFile atomically:YES];
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文