Created
July 4, 2015 07:29
-
-
Save xinzhengzhang/2db942e588c030399897 to your computer and use it in GitHub Desktop.
fuckUrlConnection
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
// | |
// ViewController.m | |
// fuckUrlConnection | |
// | |
#import "ViewController.h" | |
@interface ViewController () { | |
NSArray *_urls; | |
NSTimer *_timer; | |
int32_t _current_page; | |
} | |
@end | |
@implementation ViewController | |
- (void)viewDidLoad { | |
[super viewDidLoad]; | |
NSString *rowStr = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"urls" ofType:@"txt"] encoding:NSUTF8StringEncoding error:nil]; | |
_urls = [rowStr componentsSeparatedByString:@"\n"]; | |
_timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(schedule) userInfo:nil repeats:YES]; | |
_current_page = 0; | |
[[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes]; | |
} | |
- (void)schedule { | |
NSUInteger start = _current_page * 10; | |
NSUInteger len = MIN(_urls.count - start, 10); | |
if (len < 10) { | |
_current_page = 0; | |
} else { | |
_current_page ++; | |
} | |
NSArray *needDownloadList = [_urls subarrayWithRange:NSMakeRange(start, len)]; | |
[self downloadWithList:needDownloadList]; | |
} | |
- (void)downloadWithList:(NSArray *)arr | |
{ | |
for (NSString *url in arr) { | |
@autoreleasepool { | |
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ | |
@autoreleasepool { | |
// [self downloadWithUrlUsingCF:url]; | |
[self downloadWithUrlUsingUrlConnection:url]; | |
} | |
}); | |
} | |
} | |
} | |
- (void)downloadWithUrlUsingCF:(NSString *)url | |
{ | |
NSMutableData *d = [NSMutableData data]; | |
NSURL *urlx = [NSURL URLWithString:url]; | |
CFHTTPMessageRef messageRef = CFHTTPMessageCreateRequest(NULL, CFSTR("GET"), (__bridge CFURLRef)urlx, kCFHTTPVersion1_1); | |
CFReadStreamRef requestStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, messageRef); | |
boolean_t openStatus = CFReadStreamOpen(requestStream); | |
if (openStatus) { | |
uint8_t buf[4096]; | |
CFIndex bytesRead = 0; | |
while ((bytesRead = CFReadStreamRead(requestStream, buf, sizeof(buf))) > 0) { | |
[d appendBytes:buf length:bytesRead]; | |
memset(buf, 0, sizeof(buf)); | |
} | |
CFReadStreamClose(requestStream); | |
} | |
CFRelease(messageRef); | |
CFRelease(requestStream); | |
} | |
- (void)downloadWithUrlUsingUrlConnection:(NSString *)url | |
{ | |
[NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]] returningResponse:nil error:nil]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment