4

我正在从服务器下载 pdf 文档:

- (void)downloadSingleDocument:(NSURL *)url
{
    [pdfData release];
    pdfData = [[NSMutableData alloc] init];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    [req addValue:@"Basic **************=" forHTTPHeaderField:@"Authorization"];
    downloadConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
}

- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
    NSLog(@"Connection did receive data");
    [pdfData appendData:data];
}

在 connectionDidFinishLoading 上,我想将下载的 pdf 文件保存到 Documents 目录中的文件系统,文件名与服务器上的文件名相同。最好的方法是什么?

4

3 回答 3

5

如果您有大文件,请使用此方法:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse*)response
{
  filepath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:save_name];
  [[NSFileManager defaultManager] createFileAtPath:filepath contents:nil attributes:nil];
  file = [[NSFileHandle fileHandleForUpdatingAtPath:filepath] retain];// Here file is object of NSFileHandle and its declare in .h File

  [file seekToEndOfFile];

}



- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{

 [file seekToEndOfFile];

 [file writeData:data];
}


- (void)connectionDidFinishLoading:(NSURLConnection*)connection 
 {
  [file closeFile];
// After you download your data. you can copy your data from here to filesystem. and remove from here
 }
于 2012-04-26T04:48:00.970 回答
2

使用NSURLDownload.

抱歉,这仅适用于 Mac,不适用于 iOS。

创建一个临时文件,并将接收到的数据附加到connection:didReceiveData:. 在connectionDidFinishLoading:中,将文件移动到正确的位置,在 中connection:didFailWithError:,删除临时文件。

于 2012-04-25T11:40:16.813 回答
-1

这应该这样做

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString *documentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

    NSString *filename = [con.originalRequest.URL lastPathComponent];
    NSString *path = [documentsDirectory stringByAppendingString:filename];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager createFileAtPath:path contents:pdfData attributes:nil];

}
于 2012-04-25T11:32:12.970 回答