url定义:在WWW上,每一信息资源都有统一的且在网上唯一的地址,该地址就叫URL(UniformResourceLocator,统一资源定位符),它是WWW的统一资源定位标志,就是指网络地址。
*10.0.8.8/(服务器的地址(基地址),可以是ip地址也可以是域名)
*/my/user_list.php(服务器上特定资源(用户公开列表)的后续地址/接口名称)
*请求地址与参数之间用隔开,参数作为请求资源的限定条件;参数之间用&连接(参数格式:参数名称=参数类型对应的值)
*/
1,【同步下载,工作中从来不直接使用!!】
//对字符串封装成网址类
NSURL*url=[NSURLURLWithString:str];
//字符串的类方法,会自动根据url向服务器发起同步请求,并将请求结果返回。
//应用程序在启动之初,会自动开辟一个主线程,负责数据的初始化,视图的初始化以及视图的展示等,同步请求数据也在主线程中进行,如果耗时较长,会对主线程造成阻塞,用户体验极差
NSString*result=[NSStringstringWithContentsOfURL:urlencoding:NSUTF8StringEncodingerror:nil];
NSData*data=[resultdataUsingEncoding:NSUTF8StringEncoding];
NSDictionary/NSArray(根据数据结构选择最外层容器)*myResult=[NSJSONSerializationJSONObjectWithData:dataoptions:NSJSONReadingMutableContainerserror:nil];
把结果放到tableView中(uid/username)
2,系统自带异步下载流程
[UIApplicationsharedApplication].networkActivityIndicatorVisible=YES;
//状态栏的旋转小菊花
//根据url,生成一个请求对象
NSURLRequest*request=[NSURLRequestrequestWithURL:url];
//[NSURLRequestrequestWithURL:urlcachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:20];
//利用请求对象,创建一个NSURLConnection对象,connection对象会在客户端与服务端之间建立一个连接,并将request由客户端发到服务端
//异步:主线程负责数据的初始化,视图的初始化和界面的展示等,NSURLConnection进行数据请求的时候,会在主线程之外,单独开辟一个线程进行与服务器的交互,和接收服务器数据等耗时的操作,当数据接收完毕后,会通过代理方法自动回到主线程。我们可以在主线程进行后续的数据解析和视图刷新的操作
-(id)initWithRequest:(NSURLRequest*)requestdelegate:(id)delegate;
+(NSURLConnection*)connectionWithRequest:(NSURLRequest*)requestdelegate:(id)delegate;
//2种方法开始连接+方法/-方法
//常用的4个:1,开始响应。2,传输数据。3,成功。4,失败
//客户端收到服务端对request的响应时,调用此方法
-(void)connection:(NSURLConnection*)connectiondidReceiveResponse:(NSURLResponse*)response
{
//开始下载前清空里面的旧数据
[_downloadDatasetLength:0];
}
//当客户端收到服务端根据request传递过来的数据时(接收数据的过程),调用此方法
//可能被调用多次
-(void)connection:(NSURLConnection*)connectiondidReceiveData:(NSData*)data
[_downloadDataappendData:data];
//客户端接收数据完毕后,调用此方法
-(void)connectionDidFinishLoading:(NSURLConnection*)connection
//将_downloadData转化成数据源然后刷新tableView
[_myTableViewreloadData];
-(void)connection:(NSURLConnection*)connectiondidFailWithError:(NSError*)error
NSLog(@"联网失败,或者数据传输超时");
中途取消下载的方法
-(void)cancel;//取消连网
3,【SDWebImage】
一个非常牛b的第三方图片下载库,实现了图片的异步,并发下载,并且有缓存功能
封装的是一个category
#import"UIImageView+WebCache.h"
//2个最常用的方法:加载一个网络图片,且自动缓存
//一个有默认图片,一个没有
-(void)setImageWithURL:(NSURL*)url;
-(void)setImageWithURL:(NSURL*)urlplaceholderImage:(UIImage*)placeholder;
4,【ASIHTTPRequest】以前非常流行的下载类,现在已经不更新了,逐渐被淘汰中
ASIHTTPRequest*request=[ASIHTTPRequestrequestWithURL:[NSURLURLWithString:str]];
//设置代理
request.delegate=self;
//不同的request对象,可以通过不同的tag值来标记
request.tag=100;
//向服务器发起异步数据请求
[requeststartAsynchronous];
需要+4个framework
代理方法
//当数据获取完毕后,调用此方法
-(void)requestFinished:(ASIHTTPRequest*)request
//不同的request对象通过tag值来区分,进而进行不同的后续处理
if(request.tag==100){
//请求下来的数据都存在responseData属性中
if(request.responseData){
//可以直接获得字符串,但实际开发中,一般都用data然后json解析
NSString*result=request.responseString;
NSLog(@"结果:%@",result);
//获取数据失败时,或者网络不可以时,调用此方法
-(void)requestFailed:(ASIHTTPRequest*)request
NSLog(@"错误:%@",[request.errordescription]);
#import"ViewController.h"
@interfaceViewController()
NSMutableArray*_dataArr;
UITableView*_myTableView;
@end
@implementationViewController
-(void)viewDidLoad
[superviewDidLoad];
//Doanyadditionalsetupafterloadingtheview,typicallyfromanib.
NSLog(@"1111");
//从网络获取数据(同步的,工作中严禁使用)
NSData*data=[NSDatadataWithContentsOfURL:[NSURLURLWithString:urlStr]];
NSLog(@"222");
//将符合json格式的数据转化成字典(或数组,根据数据的最外层)
NSDictionary*dic=[NSJSONSerializationJSONObjectWithData:dataoptions:0error:nil];
_dataArr=[dicobjectForKey:@"users"];
_myTableView=[[UITableViewalloc]initWithFrame:self.view.bounds];
_myTableView.delegate=self;
_myTableView.dataSource=self;
[self.viewaddSubview:_myTableView];
#pragmamark-tableView
-(NSInteger)tableView:(UITableView*)tableViewnumberOfRowsInSection:(NSInteger)section
return_dataArr.count;
-(UITableViewCell*)tableView:(UITableView*)tableViewcellForRowAtIndexPath:(NSIndexPath*)indexPath
staticNSString*identifier=@"cellID";
UITableViewCell*cell=[tableViewdequeueReusableCellWithIdentifier:identifier];
if(!cell){
cell=[[UITableViewCellalloc]initWithStyle:UITableViewCellStyleSubtitlereuseIdentifier:identifier];
NSDictionary*dic=[_dataArrobjectAtIndex:indexPath.row];
cell.textLabel.text=[dicobjectForKey:@"uid"];
cell.detailTextLabel.text=[dicobjectForKey:@"username"];
returncell;
-(void)didReceiveMemoryWarning
[superdidReceiveMemoryWarning];
//Disposeofanyresourcesthatcanberecreated.
@interfaceViewController()
NSMutableData*_downloadData;
//网址的字符串
//转成NSURL网址类的对象
NSURL*url=[NSURLURLWithString:urlStr];
NSURLRequest*request=[NSURLRequestrequestWithURL:urlcachePolicy:0timeoutInterval:15];
NSLog(@"111");
//用来接收下载的数据
_downloadData=[[NSMutableDataalloc]init];
_dataArr=[[NSMutableArrayalloc]init];
//开始网络请求
[NSURLConnectionconnectionWithRequest:requestdelegate:self];
_myTableView.separatorColor=[UIColorredColor];
#pragmamark-connection
NSLog(@"服务器开始响应");
//每次开始响应的时候清空数据
_downloadData.length=0;
NSLog(@"接收数据,可能会被调用多次");
//下载一点放一点
NSLog(@"网络请求已完成");
NSDictionary*dic=[NSJSONSerializationJSONObjectWithData:_downloadDataoptions:0error:nil];
_dataArr.array=[dicobjectForKey:@"users"];
//数据下载完成以后,需要刷新tv
NSLog(@"网络请求失败:%@",error);
-(CGFloat)tableView:(UITableView*)tableViewheightForRowAtIndexPath:(NSIndexPath*)indexPath
return80;
UITableViewCell*cell=[tableViewdequeueReusableCellWithIdentifier:@"qqq"];
cell=[[UITableViewCellalloc]initWithStyle:UITableViewCellStyleSubtitlereuseIdentifier:@"qqq"];
UIImageView*iv=[[UIImageViewalloc]initWithFrame:CGRectMake(200,10,60,60)];
iv.tag=1;
[cell.contentViewaddSubview:iv];
UIImageView*iv=(UIImageView*)[cell.contentViewviewWithTag:1];
//头像的网址
//为一个iv加载网络图片,自带缓存
[ivsetImageWithURL:[NSURLURLWithString:imageUrlStr]];
-(void)tableView:(UITableView*)tableViewdidSelectRowAtIndexPath:(NSIndexPath*)indexPath
[tableViewdeselectRowAtIndexPath:indexPathanimated:YES];
NSLog(@"uid=%@",[[_dataArrobjectAtIndex:indexPath.row]objectForKey:@"uid"]);
ASI----------------------------------------------------------------
#import"ASIHTTPRequest.h"
@interfaceViewController()
//创建asi的网络请求
//开始异步下载
//下载成功
//打印下载的字符串
//NSLog(@"%@",request.responseString);
//request.responseData:下载的数据
NSDictionary*dic=[NSJSONSerializationJSONObjectWithData:request.responseDataoptions:0error:nil];