[英]Need assistance regarding downloading data using NSURLConnection
我的應用程序是一個消息傳遞應用程序,它也可以發送圖像文件。 我只是作為圖像上傳到Web服務器上,而另一方面只是發送其URL,使用NSURLConnection我試圖使用UIProgressView作為下載指示器下載圖像,這是我的代碼:
單擊uitableview中的下載按鈕時,將調用此方法,它將刪除下載按鈕,添加uiprogressview並開始下載
-(void)downloadImage:(UIButton *)link
{
UITableViewCell *cell = (UITableViewCell*)[link superview];
NSIndexPath *pathToCell = [tView indexPathForCell:cell];
NSMutableDictionary *checkItHasFile = [messages objectAtIndex:pathToCell.row];
NSString *str = [checkItHasFile objectForKey:@"hasFile"];
if([str isEqualToString:@"1"])
{
progress = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleBar];
progress.frame = CGRectMake(10, 50, 160, 30);
progress.progress = 0.0;
//progress.center = CGPointMake(23,21);
[cell addSubview:progress];
}
UIButton *view = [[UIButton alloc]init];
NSArray *subviews = [cell subviews];
for (view in subviews)
{
if([view isKindOfClass:[UIButton class]])
{
[view removeFromSuperview];
}
}
//
NSString *linkToPass = [NSString stringWithFormat:@"THE URL"];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:linkToPass]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection)
{
nsmd = [[NSMutableData alloc]init];
}
else
{
NSLog(@"Connection to server failed!");
}
...
此方法是NSURLConnection委托,用於指示響應,在此我正在計算響應大小
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.resourceData setLength:0];
self.filesize = [NSNumber numberWithLongLong:[response expectedContentLength]];
}
此方法是NSURLConnection委托,用於指示有關接收到的數據,我通過進行一些計算來更新進度欄
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
resourceData = [[NSMutableData alloc]init];
[self.resourceData appendData:data];
NSNumber *resourceLength = [NSNumber numberWithUnsignedInteger:[self.resourceData length]];
[self.progress setProgress:[resourceLength floatValue] / [self.filesize floatValue] animated:YES];
}
我想知道何時降級完成,所以我還可以刪除進度視圖,因為該委托方法是NSURLConnection的connectionDidFinishLoading:connection。
問題在於它會立即觸發,因此當進度視圖使下載進度動起來時,該方法也會執行,如果我在此處刪除進度視圖,則進度視圖會立即消失,而不會顯示完整的下載進度。
如何解決這個問題?
定義一個刪除進度條的方法,然后在- (void)connectionDidFinishLoading:(NSURLConnection *)connection
實現中,如果資源長度小於您確定的特定數量,請延遲調用remove方法:
[self performSelector:@selector(removeProgressBar) withObject:nil afterDelay:2];
否則立即調用相同的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.