ASIHTTPRequest 显示上传进度

ASIHTTPRequest中,要显示进度跟踪是很简单的。只需要使用一个UIProgressView控件,并简单地将它设置为requestsetUploadProgressDelegate/setDownloadProgressDelegate属性,以即

showAccurateProgress设为YES就可以了。

这就需要用到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 

然后将View Controller类设置为requestuploadProgressDelegate属性:

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);

}

原文地址:https://www.cnblogs.com/yingkong1987/p/2953782.html