轉載:http://blog.csdn.net/kmyhy/article/details/7419301
在ASIHTTPRequest中,要顯示進度跟蹤是很簡單的。只需要使用一個UIProgressView控件,並簡單地將它設置爲request的setUploadProgressDelegate/setDownloadProgressDelegate屬性,以即
把showAccurateProgress設爲YES就可以了。
但有時候我們需要爲用戶定製自己的UIProgressView顯示。比如在進度條上方加一個Label顯示當前進度(或者實際的上傳字節數):
這就需要用到ASIProgressDelegate協議了。對於上傳進度而言,需要注意其中的3個方法(還有兩個是下載進度相關的),這些方法都是可選的(不需要全部實現):
-(void)setProgress:(float)newProgress;
-(void)request:(ASIHTTPRequest *)request didSendBytes:(long long)bytes;
-(void)request:(ASIHTTPRequest *)request incrementUploadSizeBy:(longlong)newLength;
@end
ASIProgressDelegate協議使用起來很簡單。比如上面的例子,只用到了setProgress方法。
首先,在View Controller 類中聲明協議的實現:
@interfaceUploadVC : UIViewController
<ASIProgressDelegate>
然後將View Controller類設置爲request的uploadProgressDelegate屬性:
request =[[ASIFormDataRequest requestWithURL:url]retain];
⋯⋯
[requestsetUploadProgressDelegate:self];
別忘記showAccurateProgress也要設置爲YES (默認爲NO,則只顯示0%和100%):
request.showAccurateProgress=YES;//
最後是setProgress方法的實現:
-(void)setProgress:(float)newProgress{
[self.pvsetProgress:newProgress];
self.lbPercent.text=[NSString stringWithFormat:@"%0.f%%",newProgress*100];
}
如果你不想顯示百分比而顯示精確的字節數,則必須使用另外兩個方法之一:
-(void)request:(ASIHTTPRequest *)request didSendBytes:(long long)bytes;
-(void)request:(ASIHTTPRequest *)request incrementUploadSizeBy:(longlong)newLength;
二者區別在於第2個參數的不同,前者的bytes參數是每次發送的字節數(不累加),後者的newLength參數是每次發送時已發送的字節書(累加)。需要注意的是這個參數很大,爲longlong類型,轉換爲字符串時可以用%lld格式化字符串:
-(void)request:(ASIHTTPRequest*)request incrementUploadSizeBy:(long long)newLength{
NSLog(@"totalupload:%lld",newLength);
}
另外,當緩存清空時,newLength會是個負數。比如上傳完成後,緩存會被清空,此時newLength輸出爲負數:
totalupload:312791
totalupload:-131072