pokeb (owner)

Revisions

gist: 159641 Download_button fork
public
Description:
Rough example showing download bandwidth throttling with ASIHTTPRequest
Public Clone URL: git://gist.github.com/159641.git
Embed All Files: show embed
Objective-C #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
- (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];
}
    }
}