ASIProgressDelegate:實現定製的上傳進度顯示

來源:互聯網
上載者:User

在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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.