文件异步下载

主要是用到了IMIDownloader,用起来很简单,核心代码请参考附件。

 

- (void)onDownloaderReceivedData:(IMIDownloader *)aDownloader {
	NSLog(@"%@\t\tProgress:%.2f%%", aDownloader.uuid, aDownloader.progress * 100.0);
	UIProgressView *p = (UIProgressView *)[window viewWithTag:[aDownloader.uuid intValue]];
	p.progress = aDownloader.progress;
}

- (void)onFinishDownload:(IMIDownloader *)aDownloader {
	NSLog(@"%@\t\tFinish:%@", aDownloader.uuid, aDownloader.name);
}

- (void)testDownloader {
	IMIDownloadManager *dm = [IMIDownloadManager shared];
	dm.delegate = (id<IMIDownloaderDelegate>)self;
	if (![dm resume]) {
		IMIDownloader *dl = [IMIDownloader new];
		//memory size (KB) of the downloading cache, default value is 100KB
		dl.memoryCacheSize = 80;
		//uuid can be any string, but here I use an int to give tag for UIProgressView
		//that can easy trac back to update the progress
		dl.uuid = @"102";
		//give me a name, or I will guess my name
		dl.name = @"pic1.jpg";
		//customize the file, leave it blank, I can give a path
		//dl.path = @"/CUSTOMIZE/YOUR/FILE/PATH";
		dl.targetURL = @"http://dl.iteye.com/upload/attachment/0076/4387/271f6001-aaf2-3231-878a-8d74377fd17d.jpg";
		[dm addDownloader:[dl autorelease]];	//downloader will start by itself
        
		IMIDownloader *dl2 = [IMIDownloader new];
		dl2.uuid = @"4322";
		dl2.name = @"pic2.jpg";
		dl2.targetURL = @"http://dl.iteye.com/upload/attachment/0071/4676/4e0c9ec4-7485-3052-8a6b-b71520ad0838.jpg";
		[dm addDownloader:[dl2 autorelease]];
	} else {
		NSLog(@"Resume Downloading!");
	}
	
	NSArray *keys = [dm.downloaders allKeys];
	for (int i = 0; i < [keys count]; i++) {
		UIProgressView *p = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 50 * (i + 1), 320, 20)];
		p.tag = [[keys objectAtIndex:i] intValue];
		p.progressViewStyle = UIProgressViewStyleBar;
		[window addSubview:p];
		[p autorelease];
	}
	
	UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	btn.frame = CGRectMake(20, 350, 100, 40);
	[btn setTitle:@"Resume" forState:UIControlStateNormal];
	[btn addTarget:dm action:@selector(resume) forControlEvents:UIControlEventTouchUpInside];
	[window addSubview:btn];
	
	btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	btn.frame = CGRectMake(180, 350, 100, 40);
	[btn setTitle:@"Stop" forState:UIControlStateNormal];
	[btn addTarget:dm action:@selector(stop) forControlEvents:UIControlEventTouchUpInside];
	[window addSubview:btn];
}

你可能感兴趣的:(ios,异步,下载,iPhone)