1

有没有办法获得On Demand Resources下载的预计时间?

我想在全部下载之前显示警报。

[alertDownload showCustom:self image:[UIImage imageNamed:@"icon.jpg"] 
                               color:[UIColor blueColor] 
                               title:@"Download..." 
                               subTitle:@"Download in progress" 
                               closeButtonTitle:nil 
                               duration: ODR ETA];

现在我有

if (request1.progress.fractionCompleted < 1) {
 // code above
}

但是下载完成后警报不会自动消失,它会查看警报的持续时间

4

2 回答 2

1

好的,如果你能得到分数完成值并且你能测量时间,那么你就知道你还剩下多长时间了。

开始下载时,在实例变量中记录开始时间:

@interface MyClass () {
    NSTimeInterval _downloadStartTime;
}

- (void)startDownload
{
    ...
    _downloadStartTime = [NSDate timeIntervalSinceReferenceDate];
    ...
}

然后在您收到分数的通知处理程序中,使用:

double fractionComplete = 0.2;    // For example
if (fractionComplete > 0.0) {     // Avoid divide-by-zero
    NSTimeInterval now = [NSDate timeIntervalSinceReferenceDate];
    NSTimeInterval elapsed = now - _downloadStartTime;
    double timeLeft = (elapsedTime / fractionComplete) * (1.0 - fractionComplete);
}

注意:我还没有解决您显示警报对话框的问题,我认为您使用的逻辑不会起作用(您不想每次获得更新时都显示新警报)。我正在避开这整个领域,只专注于 ETA 逻辑。

于 2016-03-23T20:29:10.503 回答
0

所以,也感谢@trojanfoe 的帮助,我做到了这一点。

基本上,我在创建警报时没有设置警报持续时间,而是根据下载进度更新它。在下载完成之前,我反复将持续时间设置为 20.0f 。然后,当下载完成时,我将持续时间设置为 1.0f(因此警报将在 1 秒内消失)。

NSTimeInterval _alertDuration;

- (void)viewDidLoad {
 [request1 conditionallyBeginAccessingResourcesWithCompletionHandler:^
                                           (BOOL resourcesAvailable) 
  {
    if (resourcesAvailable) {
     // use it
    } else {
       [request1 beginAccessingResourcesWithCompletionHandler:^
                                           (NSError * _Nullable error) 
     {
           if (error == nil) {
               [[NSOperationQueue mainQueue] addOperationWithBlock:^ {
                   [alertDownload showCustom:self image:[UIImage 
                           imageNamed:@"icon.jpg"] 
                           color:[UIColor blueColor] 
                           title:@"Download..." 
                           subTitle:@"Download in progress" 
                           closeButtonTitle:nil 
                           duration:_alertDuration];
                    }
                ];
            } else {
             // handle error
            }
       }];
    }
}];

.

- (void)observeValueForKeyPath:(nullable NSString *)keyPath 
                 ofObject:(nullable id)object 
                 change:(nullable NSDictionary *)change 
                 context:(nullable void *)context {
 if((object == request1.progress) && [keyPath 
                 isEqualToString:@"fractionCompleted"]) {
    [[NSOperationQueue mainQueue] addOperationWithBlock:^ {
     if(request1.progress.fractionCompleted == 1) {
         _alertDuration = 1.0f;
     } else {
         _alertDuration = 20.0f;
     }
    }];
 }
}
于 2016-03-23T21:56:22.853 回答