Created
August 1, 2009 11:17
-
-
Save pokeb/159641 to your computer and use it in GitHub Desktop.
Rough example showing download bandwidth throttling with ASIHTTPRequest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (void)handleBytesAvailable | |
{ | |
if (![self responseHeaders]) { | |
if ([self readResponseHeadersReturningAuthenticationFailure]) { | |
[self attemptToApplyCredentialsAndResume]; | |
return; | |
} | |
} | |
if ([self needsRedirect]) { | |
return; | |
} | |
int bufferSize = 2048; | |
if (contentLength > 262144) { | |
bufferSize = 65536; | |
} else if (contentLength > 65536) { | |
bufferSize = 16384; | |
} | |
if (!throttleMeasurementDate || [throttleMeasurementDate timeIntervalSinceNow] < -1.0) { | |
[throttleMeasurementDate release]; | |
throttleMeasurementDate = [[NSDate date] retain]; | |
bytesReadSinceLastMeasurement = 0; | |
} | |
// Have we read more than 64KB in the last second? | |
if (bytesReadSinceLastMeasurement + bufferSize > 65536) { | |
bufferSize = 65536-bytesReadSinceLastMeasurement; | |
} | |
// Ensure we always read at least one byte or we'll stop receiving data | |
if (bufferSize <= 0) { | |
bufferSize = 1; | |
} | |
UInt8 buffer[bufferSize]; | |
CFIndex bytesRead = CFReadStreamRead(readStream, buffer, sizeof(buffer)); | |
// Less than zero is an error | |
if (bytesRead < 0) { | |
[self handleStreamError]; | |
// If zero bytes were read, wait for the EOF to come. | |
} else if (bytesRead) { | |
// Record how many bytes we've read for throttling | |
bytesReadSinceLastMeasurement += bytesRead; | |
[self setTotalBytesRead:[self totalBytesRead]+bytesRead]; | |
[self setLastActivityTime:[NSDate date]]; | |
//NSLog(@"%llu",[self totalBytesRead]); | |
// Are we downloading to a file? | |
if ([self downloadDestinationPath]) { | |
if (![self fileDownloadOutputStream]) { | |
BOOL append = NO; | |
if (![self temporaryFileDownloadPath]) { | |
[self setTemporaryFileDownloadPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]]; | |
} else if ([self allowResumeForFileDownloads]) { | |
append = YES; | |
} | |
[self setFileDownloadOutputStream:[[[NSOutputStream alloc] initToFileAtPath:temporaryFileDownloadPath append:append] autorelease]]; | |
[fileDownloadOutputStream open]; | |
} | |
[fileDownloadOutputStream write:buffer maxLength:bytesRead]; | |
//Otherwise, let's add the data to our in-memory store | |
} else { | |
[rawResponseData appendBytes:buffer length:bytesRead]; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment