How to show a UIProgressView for a download in my app?
I would like to show a progress bar indicating how much of a file has been downloaded in my iPhone app. I know how to set up the UIProgressView in IB and all that. But I need data such as file size in bytes to run it. How do I go about integrating such functionality with my byte download code (shown below)?
- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data
// A delegate method called by the NSURLConnection as data arrives. We just
// write the data to the file.
{
#pragma unused(theConnection)
NSInteger dataLength;
const uint8_t * dataBytes;
NSInteger bytesWritten;
NSInteger bytesWrittenSoFar;
assert(theConnection == self.connection);
dataLength = [data length];
dataBytes = [data bytes];
bytesWrittenSoFar = 0;
do {
bytesWritten = [self.fileStream writ开发者_开发问答e:&dataBytes[bytesWrittenSoFar] maxLength:dataLength - bytesWrittenSoFar];
assert(bytesWritten != 0);
if (bytesWritten == -1) {
[self _stopReceiveWithStatus:@"File write error"];
break;
} else {
bytesWrittenSoFar += bytesWritten;
}
} while (bytesWrittenSoFar != dataLength);
}
You can show show a byte-by-byte progress view if you switch to using the ASIHTTPRequest library.
I really recommend you at least check it out. It makes this stuff really simple on the iPhone and I use it for all my apps. It will do synchronous and asynchronous connections, deals with cookies and authentication, and makes composing POST requests really simple. It also has a built in network queue.
http://allseeing-i.com/ASIHTTPRequest/
精彩评论