ios - 传输过程中识别文件的完整大小

标签 ios cocoa-touch nsfilemanager

在我的 iPhone 应用程序中,我在表格 View 中显示添加到文档目录的文件的信息,只要这些文件被添加。为此,我使用 DirectoryWatcher苹果在其中一个示例代码中提供的类。

下面是显示其用法的代码块:

- (void)viewDidLoad
{
    // start monitoring the document directory…
    self.aDirectoryWatcher = [DirectoryWatcher watchFolderWithPath:[self applicationDocumentsDirectory] delegate:self];

    // scan for existing documents
    [self directoryDidChange:self.aDirectoryWatcher];
}

- (void)directoryDidChange:(DirectoryWatcher *)folderWatcher
{
    [self reconcileData];
}

表格 View 单元格中显示的信息之一是-文件大小,我获取如下:

NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:nil];
NSNumber * size = [fileAttributes objectForKey:NSFileSize];

问题是-

When I am trying to add a large file, such as a movie file, then as soon as transfer starts (copy or move operation) it invokes directoryDidChange: immediately. It did not wait unless the transfer is complete. So I always get size as 0.

对于小文件,例如图像,它工作正常。

现在我有两个问题:

  1. 有没有办法知道处于传输状态的文件的完整大小。例如。如果显示的消息是复制 30 MB 的 100 MB,我想获得 100 MB?

  2. 是否有 DirectoryWatcher 的替代方案,它仅在文件完全添加时通知?

请提出建议。

最佳答案

您当前正在查找文件系统,您应该查看下载请求的响应 header 。

例如,当您使用 NSURLConnection 下载文件时,您可以实现委托(delegate)方法 connection:didReceiveResponse: 并查看响应 header 。

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
        NSLog(@"Expected content length: %lld", httpResponse.expectedContentLength);
    }
}

要在完成时收到通知,您可以实现connectionDidFinishLoading:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // Notify download success
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // Notify error
}

关于ios - 传输过程中识别文件的完整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20010944/

相关文章:

objective-c - 以编程方式设置 UIButton 标题 UILabel 字体大小

ios - 今天扩展(应用程序组)

swift - 设置 Alamofire 自定义目标文件名而不是使用 suggestedDownloadDestination

ios - 在滑动另一个 UIView 时禁用一个 UIView 上的用户交互

iphone - 在表格左侧垂直移动表格部分

ios - iPhone 关机时 WatchKit 应用程序会发生什么情况?

ios - Xcode8 无法将多个/单个 uibuttons 连接到 swift 文件中的单个 @IBAction

ios - 具有居中 UIImageView 的 UIScrollView,如照片应用

iphone - 在 NSThread 中使用 Singleton 同步数组

objective-c - 如何在Mac的主目录中搜索特定扩展名的文件?