将文件写入 NSDocument 目录在 iPhone 中显示 UIProgressView?

Posted

技术标签:

【中文标题】将文件写入 NSDocument 目录在 iPhone 中显示 UIProgressView?【英文标题】:Write file to NSDocument directory show UIProgressView in iPhone? 【发布时间】:2013-03-28 06:12:16 【问题描述】:

我有一个来自服务器的pdf 文件。

然后我需要将文件加载到 NSDocument 目录路径并且它工作正常,但我想显示 UIProgressView 以存储每个字节。如何做到这一点,请帮助我

提前致谢

我尝试这样存储:

            NSError *error;
            NSArray *ipaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *idocumentsDir = [ipaths objectAtIndex:0];
            NSString *idataPath = [idocumentsDir stringByAppendingPathComponent:@"File"];
            NSLog(@"idataPath:%@",idataPath);

            //Create folder here
            if (![[NSFileManager defaultManager] fileExistsAtPath:idataPath])
            
                [[NSFileManager defaultManager] createDirectoryAtPath:idataPath withIntermediateDirectories:NO attributes:nil error:&error];
            
  // Image Download here
            NSString *fileName = [idataPath stringByAppendingFormat:@"/image.jpg"];
            NSLog(@"imagePathDOWNLOAD:%@",fileName);

            NSData *pdfData1 = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:[URLArray objectAtIndex:a]]];
            [pdfData1 writeToFile:fileName atomically:YES];

【问题讨论】:

从 Web URL 下载或存储在 Documents 中时需要进度吗? 存储在文档中时 【参考方案1】:

你可以使用 NSURLConnection 类来实现进度条:

.h:
NSMutableData *responseData;
NSString *originalFileSize;
NSString *downloadedFileSize;

.m:
- (void)load 
    NSURL *myURL = [NSURL URLWithString:@""];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL
                                                cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                         timeoutInterval:60];

[[NSURLConnection alloc] initWithRequest:request delegate:self];


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
responseData = [[NSMutableData alloc] init];
originalFileSize = [response expectedContentLength];


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
[responseData appendData:data];

downloadedFileSize = [responseData length];
progressBar.progress = ([originalFileSize floatValue] / [downloadedFileSize floatValue]);


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
[responseData release];
[connection release];



- (void)connectionDidFinishLoading:(NSURLConnection *)connection 

NSLog(@"Succeeded! Received %d bytes of data",[responseData lengtn]);


如有任何疑问,请告诉我。

【讨论】:

以上是关于将文件写入 NSDocument 目录在 iPhone 中显示 UIProgressView?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Objective-C 的 NSDocument 目录中保存和获取多个 pdf 文件?

设置 NSDocument 以保存非本机类型

使用 NSDocument 打开任何文件夹

NSDocument 和键盘(如 keyDown)

基于 NSDocument 的应用程序:在 NSSavePanel 中选择默认文件类型

从 NSObject 获取 NSDocument