如何使用AFHTTPRequestOperation更新MBProgressHud

时间:2012-02-17 12:28:28

标签: singleton afnetworking mbprogresshud

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

示例包括:

  • AFNetworking;
  • Inapp购买(来自RayW);
  • MBProgressHud;

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

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

  • 我在Viewcontroller中按下按钮,将显示hud;

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

      • - >之后,将在单例类中调用AFHTTPRequestOperation以下载文件;

        • --->在此下载过程中,我使用setDownloadProgressBlock方法进行处理。

但是我如何将进度信息发送回viewcontroller中的hud?

感谢。

2 个答案:

答案 0 :(得分:3)

这是我在@mattt建议之后对类似问题所做的。 我的Singleton InApp助手productDownloadURL ivar和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 / success / failure块,如下所示:

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 MBProgressHUD。您还可以使用MBProgressHUDModeDeterminate模式增强进度显示。

答案 1 :(得分:2)

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

enqueueHTTPOperation:的正文中,设置进度视图的setDownloadProgressBlock属性(您需要将progress除以bytesReceived,以便在0.0和1.0之间进行标准化。