我从服务器下载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目录中的文件系统,文件名与服务器上的文件名相同。 最好的方法是什么?
答案 0 :(得分: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
}
答案 1 :(得分:2)
很抱歉,这只适用于Mac,不适用于iOS。
创建一个临时文件,并在connection:didReceiveData:
中将收到的数据附加到其中。在connectionDidFinishLoading:
中,将文件移至正确的位置,然后在connection:didFailWithError:
中删除临时文件。
答案 2 :(得分:-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];
}