ASIHTTPREQUEST网络加载图片
好久没写了,最近事比较多,心比较乱,再加上搞这个ASIHTTPREQUEST花了不少时间,所以更得慢了些。
现在立刻为大家更上新的东西,ASIHTTPREQUEST是ios网络开发的一个开源的库,是网络编程的利器,功能及其强大,使用起来也不是很难。ASIHTTPRequest就是一个对CFNetwork API进行了封装,并且使用起来非常简单的一套API,适用于基本的HTTP请求,和基于REST的服务之间的交互。
ASIHTTPRequest功能很强大,主要特色如下:
- l 通过简单的接口,即可完成向服务端提交数据和从服务端获取数据的工作
- l 下载的数据,可存储到内存中或直接存储到磁盘中
- l 能上传本地文件到服务端
- l 可以方便的访问和操作请求和返回的Http头信息
- l 可以获取到上传或下载的进度信息,为应用程序提供更好的体验
- l 支持上传或下载队列,并且可获取队列的进度信息
- l 支持基本、摘要和NTLM身份认证,在同一会话中授权凭证会自动维持,并且可以存储在Keychain(Mac和iOS操作系统的密码管理系统)中
- l 支持Cookie
- l 当应用(iOS 4+)在后台运行时,请求可以继续运行
- l 支持GZIP压缩数据
- l 内置的ASIDownloadCache类,可以缓存请求返回的数据,这样即使没有网络也可以返回已经缓存的数据结果
- l ASIWebPageRequest –可以下载完整的网页,包括包含的网页、样式表、脚本等资源文件,并显示在UIWebView /WebView中。任意大小的页面都可以无限期缓存,这样即使没有网络也可以离线浏览
- l 支持客户端证书
- l 支持通过代理发起Http请求
- l 支持带宽限制。在iOS平台,可以根据当前网络情况来自动决定是否限制带宽,例如当使用WWAN(GPRS/Edge/3G)网络时限制,而当使用WIFI时不做任何限制
- l 支持断点续传
- l 支持同步和异步请求
2.1.1安装说明
如果想在iOS项目中使用ASIHTTPRequest,需要在项目中进行简单的配置,步骤如下:
1) 添加文件
往一个Xcode项目中添加第三方类库文件,有两种方式:
1. 第一种方式,在Finder中打开需要添加到文件或文件夹,在Xcode中打开要添加文件的项目,然后选中要添加的文件或文件夹,将它从Finder中拖 到Xcode中,然后释放。在弹出的对话框中,如果文件已经拷贝到了项目文件目录中,则不需要选中“Copy items”的复选框;如果文件没有拷贝到项目文件目录,就需要选中“Copy items”的复选框,这样Xcode会自动把文件复制到项目文件目录下。如下图所示:
2. 第二种方式,在Xcode中,在要添加文件的分组下点右键,选中“Add Files to “My
Project”…”菜单,在弹出的文件浏览对话框中选中要添加到文件或文件夹。如果要添加文件已经拷贝到了项目文件目录中,则不需要选中“Copy
items”的复选框;如果文件没有拷贝到项目文件目录,就需要选中“Copy
items”的复选框,这样Xcode会自动把文件复制到项目文件目录下。如下图所示:
根据上面的说明,添加ASIHTTPRequest相关文件到Xcode项目中,所需文件列表如下:
ASIHTTPRequestConfig.h
ASIHTTPRequestDelegate.h
ASIProgressDelegate.h
ASICacheDelegate.h
ASIHTTPRequest.h
ASIHTTPRequest.m
ASIDataCompressor.h
ASIDataCompressor.m
ASIDataDecompressor.h
ASIDataDecompressor.m
ASIFormDataRequest.h
ASIInputStream.h
ASIInputStream.m
ASIFormDataRequest.m
ASINetworkQueue.h
ASINetworkQueue.m
ASIDownloadCache.h
ASIDownloadCache.m
ASIAuthenticationDialog.h
ASIAuthenticationDialog.m
Reachability.h (在源码的 External/Reachability 目录下)
Reachability.m (在源码的 External/Reachability 目录下)
2) 链接相关类库
1. 选中项目
2. 选中目标
3. 跳转到“Build Phases”标签
4. 展开“Link Binary With Libraries”分组
5. 点击“+”添加类库
如下图所示:
6. 从列表中选择CFNetwork.framework,然后点击“Add”按钮。
7. 按照上一步相同的方法添加:SystemConfiguration.framework, MobileCoreServices.framework,CoreGraphics.framework和libz.1.2.3.dylib这几个类库。
8. 添加完后,可以将添加好的一起类库拖到Xcode项目的Frameworks目录下
2.1.2使用说明
ASIHTTPRequest有很多功能,所有功能说明都可以在其官方网站的相关文档中查到,限于篇幅,本章仅简单介绍一下如何使用ASIHTTPRequest来进行同步Http请求和异步Http请求。在后面的章节中,我们还会用到它的一些其他功能。
在使用ASIHTTPRequest之前,请确认已经正确安装,然后在需要应用它的代码文件头部,加入:
#import “ASIHTTPRequest.h”
这样就可以在代码中使用ASIHTTPRequest相关的类。
好了,上面都是安装的过程,接下来为大家呈上代码,这个程序主要实现的是在tableview中加载网络图片,并显示进度条,不过进度条有点问题,就是和图片的顺序不对应,这个bug楼主至今仍未解决。如果不用进度条的话就把它注销,这样就没问题了。不知道有没有高手能提出解决方案的。
效果图:图片很漂亮哦
#import <UIKit/UIKit.h> #import "ASIHTTPRequest.h"//头文件 @class ASINetworkQueue; @interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource> { ASINetworkQueue *networkQueue; ASIHTTPRequest *requestImage; BOOL failed ; NSInteger proTag; } @property (retain,nonatomic)UITableView *imageTableView; @property (retain,nonatomic)NSArray *imageArray;//为什么用不可变数组,因为在加入数组之前数量就知道了 @property (retain,nonatomic)UIImageView *imageview ; @property (retain,nonatomic)NSMutableArray *imagePicArray;//为什么用可变数组呢,因为在加入数组之前不知道有几张图片 @end
.m文件
#import "ViewController.h" #import "ASINetworkQueue.h" @implementation ViewController @synthesize imageTableView; @synthesize imageArray; @synthesize imageview; @synthesize imagePicArray; - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } #pragma mark - View lifecycle - (void)viewDidLoad { [super viewDidLoad]; UINavigationBar *navBar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)]; UINavigationItem *item = [[UINavigationItem alloc]initWithTitle:@"title"]; UIBarButtonItem *start = [[UIBarButtonItem alloc]initWithTitle:@"开始" style:UIBarButtonItemStyleDone target:self action:@selector(downLoadImage)]; item.leftBarButtonItem = start; NSArray *items = [NSArray arrayWithObjects:item, nil]; navBar.items = items; [self.view addSubview:navBar]; [navBar release]; self.imageview=[[[UIImageView alloc] init] autorelease];//控件对象,数组都要初始化 self.imagePicArray = [[[NSMutableArray alloc]initWithCapacity:0]autorelease]; UITableView *table = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStylePlain]; table.delegate = self; table.dataSource = self; self.imageTableView = table; [self.view addSubview:self.imageTableView]; [table release]; NSArray *array = [[NSArray alloc]initWithObjects:@"http://www.jjpfk.com.cn/files/2008080609440769047.jpg",@"http://www.fx120.net/lady/UploadFiles_159357/201010/20101015172254784.jpg",@"http://www.fx120.net/eden/UploadFiles_971/201108/20110808125024324.jpg",@"http://attach.bbs.china.com.cn/forum/131_29861_d74fcf797ef48a9.jpg",@"http://www.5ijk.net/upload/2011_09/11090913402389.jpg",@"http://www.3270999.com/uploads/allimg/111022/2-111022103R2455.jpg", nil]; self.imageArray = array; } #pragma mark -tableviewDelegate- - (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"cell"; NSLog(@"------进来"); UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (cell == nil) {//初始化了cell != nil,不会进来 cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; UIProgressView *pro = [[UIProgressView alloc]initWithFrame:CGRectMake(100, 20, 200, 20)]; pro.tag = indexPath.row + 2000 ; NSLog(@"pro.tag==%d",pro.tag); [cell.contentView addSubview:pro]; [pro release]; } if (imagePicArray.count > indexPath.row){//当数组里的数据个数大于indexPath.row的时候再去加载,不然会crash [cell.imageView setImage:[imagePicArray objectAtIndex:indexPath.row]]; } return cell; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.imageArray.count; } #pragma mark -下载- - (void)downLoadImage { if (!networkQueue) { networkQueue = [[ASINetworkQueue alloc]init]; } failed = NO; [networkQueue reset]; [networkQueue setRequestDidFinishSelector:@selector(imageDownloadComplete:)];//队列加载完成时调用的方法 [networkQueue setRequestDidFailSelector:@selector(imageFetchFailed:)];//队列加载出错时调用的方法 [networkQueue setShowAccurateProgress:YES]; [networkQueue setDelegate:self]; for (int i = 0; i < self.imageArray.count; i++){ ASIHTTPRequest *requestImag = [[ASIHTTPRequest alloc]initWithURL:[NSURL URLWithString:[self.imageArray objectAtIndex:i]]]; requestImag.tag = i+1000; [requestImag setDownloadDestinationPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png",i]]]; // [networkQueue setDownloadProgressDelegate:(UIProgressView*)[self.view viewWithTag:i+2000]];//显示全局人物下载的进度 [requestImag setDownloadProgressDelegate:(UIProgressView *)[self.view viewWithTag:i+2000]];//显示单个任务下载的进度,用这种方法可以取到任何控件的tag // [requestImag setUserInfo:[NSDictionary dictionaryWithObject:@"request1" forKey:@"image1"]];//不知道干什么用的 [requestImag setAllowResumeForFileDownloads:YES];//允许断点续传 [networkQueue addOperation:requestImag]; [requestImag release]; } [networkQueue go];//队列开始加载 } - (void)imageDownloadComplete:(ASIHTTPRequest*)request//加载完成时 { UIImage *image = [UIImage imageWithContentsOfFile:[request downloadDestinationPath]]; if (image) { //UIImageView *imageviews = (UIImageView *)[self.view viewWithTag:request.tag]; //用这种方式可以获取全局view的tag,根据tag调用不同的方法。 //imageviews.image = image; self.imageview.image = image; [imagePicArray addObject:self.imageview.image]; } [self.imageTableView reloadData]; } - (void)imageFetchFailed:(ASIHTTPRequest *)request//加载失败时 { if (!failed) { if ([[request error] domain] != NetworkRequestErrorDomain || [[request error] code] != ASIRequestCancelledErrorType) { UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:@"Download failed" message:@"Failed to download images" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease]; [alertView show]; } failed = YES; } } - (void)viewDidUnload { [super viewDidUnload]; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; } - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); } - (void)dealloc { [imageview release]; [super dealloc]; } @end
还有就是那个小bug,图片是从第一行开始加载的,但进度条不对应,希望有高手指出帮我解决。