我正在尝试创建一个 iPhone 应用程序,如下图所示:
在这个我动态地添加一些图像视图到 uiscroll 视图中。每个 imageview 包含一个 UIButton 和 UIProgressView。当点击每一个它应该不同的 url 并且每个 url 的加载应该出现在相应的 UIProgressView 上。我正在使用异步方法,它应该同时加载多个进度视图。这是我使用的代码,
- (void)startDownload:(id)sender {
UIButton *btn = (UIButton *)sender;
int btnTag = btn.tag;
selectedTag = btn.tag;
for (int x=0; x < [urlArray count]; x++) {
if (btnTag == x) {
NSURL *url = [NSURL URLWithString:[urlArray objectAtIndex:x]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *theConnection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(@"Expected length: %lld ",response.expectedContentLength);
}];
if (theConnection) {
receivedData = [NSMutableData data];
}else {
NSLog(@"Connection failed");
}
}
}
}
- (void)makeMyProgressMove{
UIImageView *image = (UIImageView *)[mainView viewWithTag:selectedTag];
UIProgressView *currentProgress = (UIProgressView *)[image viewWithTag:selectedTag];
NSLog(@"Prog tag: %d",currentProgress.tag);
if(currentProgress)
{
float actualProgress = (_receivedDataBytes / (float)_totalFileSize);
currentProgress.progress = actualProgress;
} else {
NSLog( @"couldn't get the progress view for the image with tag: %d", selectedTag );
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
_totalFileSize = response.expectedContentLength;
receivedData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
_receivedDataBytes += [data length];
NSLog(@"Receiving data: %2f", _receivedDataBytes / (float)_totalFileSize);
if ((_receivedDataBytes / (float)_totalFileSize) < 1) {
[self performSelectorOnMainThread: @selector(makeMyProgressMove) withObject: NULL waitUntilDone:NO];
}
else if ((_receivedDataBytes / (float)_totalFileSize) == 1){
[self performSelectorOnMainThread: @selector(makeMyProgressMove) withObject: NULL waitUntilDone:NO];
_receivedDataBytes = 0;
_totalFileSize = 0;
}
[receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
}
但它不起作用。任何的想法?