3

我下载了一些例子来学习 Ios。

示例包括:

  • AF网络;
  • 应用内购买(来自 RayW);
  • MBProgressHud;

在我的视图控制器中,我按下一个触发 Inapp 购买单例示例的 UI 按钮,并开始使用 AFHTTPRequestOperation 从我的服务器下载文件。这部分通信有效。但我想要实现的是在下载时更新我的​​ hud。由于文件> 10Mb。

所以,问题是我如何用下载进度更新 hud?我试着把它画下来。

  • 我按下 Viewcontroller 中的按钮,就会显示 hud;

    • --> 请求将发送到处理网络部分的 Singleton InApp 助手类;

      • --> 之后会在单例类中调用AFHTTPRequestOperation来下载文件;

        • ---> 在此下载过程中,我使用 setDownloadProgressBlock 方法来获取进度。

但是我如何将进度信息发送回视图控制器中的 hud?

谢谢。

4

2 回答 2

3

这就是我按照@mattt 的建议对类似问题所做的。我的 Singleton InApp 助手productDownloadURLivar 和一个prepareForDownload返回AFHTTPRequestOperation给调用者的方法:

- (AFHTTPRequestOperation * )prepareForDownload:(NSString *)productIdentifier
{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:_productDownloadURL]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:productIdentifier];
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];

    return  operation;
}

我的RootViewController通过使用AFHTTPRequestOperation和设置downloadProgress//块发出请求successfailure如下所示:

AFHTTPRequestOperation *operation = [[InAppRageIAPHelper sharedHelper] prepareForDownload:productIdentifier];
[operation setDownloadProgressBlock:^(NSInteger bytesRead, NSInteger totalBytesRead, NSInteger totalBytesExpectedToRead) {
     float percentDone = ((float)((int)totalBytesRead) / (float)((int)totalBytesExpectedToRead));    
     [(UIProgressView *)_hud.customView setProgress:percentDone];
     _hud.labelText = [NSString stringWithFormat:@"%f",percentDone];
 }];

 [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
   _hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"success.png"]];
   [self performSelector:@selector(dismissHUD:) withObject:nil afterDelay:1.5];
 } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
   _hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error.png"]];
 }];
 [operation start];

hud是一个MBProgressHUDMBProgressHUDModeDeterminate您还可以使用模式增强进度显示。

于 2012-03-12T17:40:08.347 回答
2

从控制器发出请求,并在创建操作并将其排入变量时保留对操作的引用(您可以通过使用创建中间操作对象HTTPOperationWithRequest:success:failure并手动执行enqueueHTTPOperation:.

在 的主体中setDownloadProgressBlock,设置progress进度视图的属性(您需要除以bytesReceivedbytesExpectedToReceive在 0.0 和 1.0 之间进行标准化。

于 2012-02-20T20:47:11.770 回答