Saturday, November 20, 2010

TTURLRequest tracking download progress

OK, I needed to present a progress bar while downloading a fairly large file to my app.
This presented three challanges:
1. Presenting a progress bar. Well, with three20 this is real easy - I created a view controller that is presented modally and used the Three20 ActivityLabel:
- (void) loadView
{
    [super loadView];
    _downloadProgressLabel = [[TTActivityLabel alloc] initWithStyle:TTActivityLabelStyleBlackBezel];
    _downloadProgressLabel.progress = _progress;
    _downloadProgressLabel.text = @"Downloading My File...";
    [_downloadProgressLabel sizeToFit];
    _downloadProgressLabel.center = self.view.center;
    [self.view addSubview:_downloadProgressLabel];
}

- (void) setProgress:(float)inProgress
{
    _progress = inProgress;
    _downloadProgressLabel.progress = _progress;
}

2. Getting the progress from an asynchronous TTURLRequest. Well, the TTURLRequestDelegate protocol has a method called requestDidUploadData, but this is only used by uploads (POST with some body). Well, thought I will implement something, but a quick google search found me that: https://github.com/facebook/three20/pull/288
So, I was not the first to tackle this... thanks Cemal Eker!

3. After implementing this, I still had an issue. I found out that I made a stupid mistake. I was waiting in a loop for the request to finish doing [NSThread sleepForTimeInterval:0.5]. This caused both the URLRequest to not function as well as my view controller to not show up..
So, don't do that, you are going to get a requestDidFinish in your delegate, so no need to sit in a loop...