UI:网络请求
阅读原文时间:2023年07月15日阅读:3

JSON 外层是一个数组或者字典

富文本(相对来说比较安全)、超文本,https安全超文本协议

NSURL

NSURL *url = [[NSURL alloc]initWithString:@"http://img.zcool.cn/community/0332de1559f800a32f875370ac09559.jpg"];

NSData *data = [NSData dataWithContentsOfURL:url];

UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10,355,500)];

imageview.image = [UIImage imageWithData:data];

[self.window addSubview:imageview];

get(能够看到)post(不能够看到请求的内容)

区别

1(参数)

get 请求就是将服务器地址与参数拼接在一块,形成请求网址(分同步和异步请求两种)

post  将服务器地址与参数分开,参数以请求体的形式(把所有的参数放到字典里)提交服务器

2(安全)get  不是很安全,post 相对比较安全

3(大小) get 最多是255个字节,而post没有大小限制

程序的主线程

多线程  是指从软件或者硬件上实现多个线程并发执行的技术。具有多线程能力的计算机因有硬件支持而能够在同一时间执行多于一个线程,进而提升整体处理性能。

同步请求与异步请求的区别:

同步请求:网络所有的请求任务都由主线程完成,(如:做饭,先去买好菜,才开火做饭,始终都是一个人单独去做)对于程序而言,在请求任务的时候,不能再响应用户点击事件。当主线程在处理网络请求时候,所有的用户交互无法处理,用户体验差。

异步请求:网络请求的任务由子线程完成,当子线程在处理网络请求时,主线程依然可以处理用户交互,不会影响用户的点击事件的交互的处理,用户体验很好

GET 方法请求数据

同步请求

创建网址对象

NSString * urlString =  [NSString stringWithFormat:@"http://api.map.baidu.com/place/v2/searchquery=%@&region=%@&output=json&ak=6E823f587c95f0148c19993539b99295",@"大学",@"郑州"];

对于中文的格式要修改编码格式

NSString * newString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

创建UNSURL 对象

NSURL * nsurl = [NSURL URLWithString:newString];

创建请求对象

NSURLRequest * request= [NSURLRequest  requestWithURL:nsurl];

同步请求

NSURLResponse * response = nil;服务器的响应对象 存储服务器响应信息;返回信息的数据大小、长度、以及数据的类型

NSError * error = nil;存储链接错误的信息,如:链接失败,突然断网、网络中断等

NSData * data =  [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];data 就是通过网址在服务器上请求下来的数据

使用系统提供的 JSON 的解析方式

NSMutableDictionary  * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

NSArray * arr =  dic[@"results"];

存储数据源

在存储数据源之后要注意,刷新数据。

异步请求数据

创建网址字符串

NSString * url = [NSString  StringWithFormat:

@"http://api.map.baidu.com/place/v2/search?query=%@&region=%@&output=json&ak=6E823f587c95f0148c19993539b99295",@"医院",@"郑州"];

];

NSString * newURL= [url stringByAddingPrecentEscapesUsingEncoding:NSUTF8StringEncoding];

创建一个真实的 NSURL 对象

NSURL * URL= [NSURL URLWithString:newUrl];

根据一个网址对象去创建一个请求对象,

NSURLRequest * request = [NSURLRequest requestWithURL:URL];

链接服务器发起网络请求

(第一种 block )

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {//synchronous 同步的

//data 服务器返回来的数据

[self parseDataWithData:data];

}];

解析数据

-(void)parseDataWithData:(NSData * )data{

//使用系统提供的 JSON 的解析方式

NSMutableDictionary  * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

NSArray * arr =  dic[@"results"];

//每次清空数据源

[_dataSouce removeAllObjects];

//遍历数组

for (NSDictionary * dicc in arr) {

Model * model = [[Model alloc]initWithDic:dicc];//添加数据源

[_dataSouce addObject:model];//存储数据源

}

[self.tableView reloadData];

}

( 第二种  代理 ) 注意对应的类要遵循 NSURLConnectionDelegate 协议 并实现一些方法(有些方法)

[NSURLConnection connnectionWithRequest:request delegate:self];

实现协议的方法

//收到响应时候

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

//在链接服务器的过程中只会走一次

self.receiveData  = [NSMutableData data];

}

//收到服务器的数据时候

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{

[self.receiveData appendData:data];

}

//链接结束的时候

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{

//解析数据

[self parseDataWithData:self.receiveData];

}

//链接失败的时候

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{

NSLog(@"链接失败");

}

POST 方法请求数据

(同步请求数据)

创建网址字符串

//method=album.channel.get&appKey=myKey&format=json&channel=t&pageNo=1&pageSize=10

NSString * str = [NSString stringWithFormat:KURL];

NSURL * Url = [NSURL URLWithString:str];

创建请求对象

NSMutableURLRequest * request =[NSMutableURLRequest requestWithURL:Url];

处理参数字符串

NSString *  parmStr = [NSString stringWithFormat:@"method=album.channel.get&appKey=myKey&format=json&channel=t&pageNo=1&pageSize=10"];

设置请求体。将参数字符串转化为NSData 对象

[request setHTTPBody:[parmStr dataUsingEncoding:NSUTF8StringEncoding]];

设置请求方式

[request setHTTPMethod:@"POST"];//如果不设置的话,默认的为 get

同步链接

NSURLResponse * response = nil;

NSError * error = nil;

NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

解析

[self parseData:data];

}

-(void)parseData:data{

//系统 JSON 解析

NSDictionary * dic =  [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

NSLog(@"%@",dic);

}

异步请求

-(void)RhandelAction:(UIBarButtonItem *)sender{

创键网址字符串

NSString * str = [NSString stringWithFormat:KURL];

//真实的网址对象

NSURL * URl = [NSURL URLWithString:str];

//请求对象的创建

NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:URl];

//处理参数部分

NSString * parmStr = [NSString stringWithFormat:@"method=album.channel.get&appKey=myKey&format=json&channel=t&pageNo=1&pageSize=10"];

//设置请求体 将参数字符串转化为 NSData

[request setHTTPBody:[parmStr dataUsingEncoding:NSUTF8StringEncoding]];

//请求方式为 post

[request setHTTPMethod:@"POST"];

/*

//创建链接

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

[self parseData:data];

}];

*/

//代理形式

[NSURLConnection connectionWithRequest:request delegate:self];

}

#pragma mark-----NSURLConnection 协议

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

self.dataSource = [NSMutableData data];

}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{

[self.dataSource appendData:data];

}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{

[self parseData:self.dataSource];

}

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

在 NSURLConnectionDataDelegate 协议里面 有一个仅仅走一次的方法可以计算出来请求数据的大小

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

response.expectedContentLength;//数据的总的大小

}

代码:

#pragma mark (AppdeleGate.h文件)————————————————————————————————————————————————————

#pragma mark (.m文件)————————————————————————————————————————————————————

MainTabBarController \* mainVC =\[\[MainTabBarController alloc\]init\];  
self.window.rootViewController = mainVC;  
\[mainVC release\];

return YES;

Appdelegate文件

#pragma mark (MainTabBarController.h文件)————————————————————————————————————————————————————

#import

@interface MainTabBarController : UITabBarController

@end

#pragma mark (.m文件)————————————————————————————————————————————————————

//
// MainTabBarController.m
// NSURL_Request

#import "MainTabBarController.h"
#import "GetViewController.h"
#import "PostViewController.h"
#import "ImageViewController.h"

@interface MainTabBarController ()

@end

@implementation MainTabBarController

  • (void)viewDidLoad {
    [super viewDidLoad];
    GetViewController * getVC = [[GetViewController alloc]initWithStyle:UITableViewStylePlain];
    getVC.tabBarItem.title = @"get方式请求数据";
    getVC.tabBarItem.image = [UIImage imageNamed:@"tabbar_discover@2x" ];
    getVC.navigationItem.title = @"get";
    UINavigationController * getNavl = [[UINavigationController alloc]initWithRootViewController:getVC];

    PostViewController * PostVC = [[PostViewController alloc]initWithStyle:UITableViewStylePlain];
    PostVC.tabBarItem.title = @"post方式请求数据";
    PostVC.tabBarItem.image = [UIImage imageNamed:@"tabbar_mainframe@2x" ];
    PostVC.navigationItem.title = @"post";
    UINavigationController * postNav = [[UINavigationController alloc]initWithRootViewController:PostVC];

    ImageViewController * imageVC = [[ImageViewController alloc]init];
    imageVC.tabBarItem.image = [UIImage imageNamed:@"tabbar_badge@2x"];
    imageVC.tabBarItem.title = @"图片请求";
    imageVC.navigationItem.title = @"图片";
    UINavigationController * imageNav = [[UINavigationController alloc]initWithRootViewController:imageVC];
    NSArray * arry = @[getNavl,postNav,imageNav];
    self.viewControllers = arry;

    [getVC release];
    [PostVC release];
    [imageVC release];
    [imageNav release];

}

  • (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

  • (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    }
    */

@end

MainTabBarController文件

#pragma mark (GetViewController.h文件)————————————————————————————————————————————————————

#import

@interface GetViewController : UITableViewController

@end

#pragma mark (.m文件)————————————————————————————————————————————————————

//
// GetViewController.m
// NSURL_Request

#import "GetViewController.h"
#import "Model.h"

@interface GetViewController ()
@property(nonatomic,retain)NSMutableArray * dataSouce;
@property(nonatomic,retain)NSMutableData * receiveData;
@end
/*
1.参数
get 请求就是将服务器地址与参数拼接在一块,形成请求网址 而 post 将服务器地址与参数分开,参数以请求体的形式(把所有的参数放到字典里)提交服务器(相对安全)
2.大小
get 的字符串的大小最大为 255 个字节,而post 请求没有限制
3.安全性
get 因为参数是在网址中,所以是不安全的。而 post 请求是参数是作为参数体提交,相对来说是安全的
4.用途 get请求用于请求数据(下载数据) post 请求而言,所用于提交数据,可以做一些上传的工作
*/

@implementation GetViewController

-(NSMutableArray *)dataSouce{
if (!_dataSouce) {
self.dataSouce = [NSMutableArray arrayWithCapacity:];
}
return _dataSouce;
}

  • (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"同步" style:UIBarButtonItemStylePlain target:self action:@selector(handleSynchronizeRequest:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"异步" style:UIBarButtonItemStylePlain target:self action:@selector(handleAsynchronize:)];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reue"];
    }
    //GET 同步
  • (void)handleSynchronizeRequest:(UIBarButtonItem *)sender{
    //创建网址对象
    // NSString * urlString = @"http://api.map.baidu.com/place/v2/search?query=酒店&region=郑州&output=json&ak=6E823f587c95f0148c19993539b99295";
    NSString * urlString = [NSString stringWithFormat:@"http://api.map.baidu.com/place/v2/search?query=%@&region=%@&output=json&ak=6E823f587c95f0148c19993539b99295",@"大学",@"郑州"];
    //对于中文的格式要修改编码格式
    NSString * newString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //创建 NSURL 对象
    NSURL * nsurl = [NSURL URLWithString:newString];
    //创建请求对象
    NSURLRequest * request = [NSURLRequest requestWithURL:nsurl];
    //同步请求
    NSURLResponse * response = nil;//服务器的响应对象 存储服务器响应信息;返回信息的数据大小、长度、以及数据的类型
    NSError * error = nil;//存储链接错误的信息,如:链接失败,突然断网、网络中断等
    NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];//data 就是通过网址在服务器上请求下来的数据
    NSLog(@"数据类型:%@",[response class]);
    //解析数据 供界面上显示
    [self parseDataWithData:data];

}
-(void)parseDataWithData:(NSData * )data{
//使用系统提供的 JSON 的解析方式
NSMutableDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSArray * arr = dic[@"results"];
//每次清空数据源
[_dataSouce removeAllObjects];
//遍历数组
for (NSDictionary * dicc in arr) {
Model * model = [[Model alloc]initWithDic:dicc];//添加数据源
[_dataSouce addObject:model];//存储数据源
}
[self.tableView reloadData];
NSLog(@"%@",_dataSouce);
}
//GET 异步

  • (void)handleAsynchronize:(UIBarButtonItem *)sender{
    //1.创建网址字符串
    NSString * urlString = [NSString stringWithFormat:@"http://api.map.baidu.com/place/v2/search?query=%@&region=%@&output=json&ak=6E823f587c95f0148c19993539b99295",@"医院",@"郑州"];
    NSString * newUrl = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //创建一个真实的 NSURL 对象
    NSURL * URL= [NSURL URLWithString:newUrl];
    //根据网址对象去创键一个请求对象
    NSURLRequest * request = [NSURLRequest requestWithURL:URL];
    //链接服务器发起请求
    //异步请求第一种方式(block 方式) *********************************
    /*
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    //data 服务器返回来的数据
    [self parseDataWithData:data];
    }];
    */
    //异步请求第二种方式(代理 方式) *********************************
    [NSURLConnection connectionWithRequest:request delegate:self];

}

#pragma mark ------ NSURLConnection 协议
//收到响应时候
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
//在链接服务器的过程中只会走一次
self.receiveData = [NSMutableData data];
}
//收到服务器的数据时候
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.receiveData appendData:data];
}
//链接结束的时候
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
//解析数据
[self parseDataWithData:self.receiveData];
}
//链接失败的时候
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"链接失败");
}

  • (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

#pragma mark - Table view data source

  • (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return ;
    }

  • (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSouce.count;
    }

  • (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reue" forIndexPath:indexPath];
    Model * model = _dataSouce[indexPath.row];
    NSLog(@"%@ %@ %@ %@",model.name,model.address,model.telephone,_dataSouce);
    NSLog(@"mode- %@",model.name);
    cell.textLabel.text = model.name;

    return cell;
    }

/*
// Override to support conditional editing of the table view.

  • (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
    }
    */

/*
// Override to support editing the table view.

  • (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Delete the row from the data source
    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
    }
    */

/*
// Override to support rearranging the table view.

  • (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
    }
    */

/*
// Override to support conditional rearranging of the table view.

  • (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
    }
    */

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

  • (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    }
    */

@end

GetViewController文件

#pragma mark (.h文件)————————————————————————————————————————————————————

#import

@interface PostViewController : UITableViewController

@end

#pragma mark (.m文件)————————————————————————————————————————————————————

//
// PostViewController.m

#define KURL @"http://api.tudou.com/v3/gw"

#import "PostViewController.h"

@interface PostViewController ()
@property(nonatomic,retain)NSMutableData * dataSource;
@end

@implementation PostViewController

  • (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpView];
    }

-(void)setUpView{
UIBarButtonItem * left = [[UIBarButtonItem alloc]initWithTitle:@"同步" style:UIBarButtonItemStylePlain target:self action:@selector(LhandelAction:)];
self.navigationItem.leftBarButtonItem = left;
[left release];

UIBarButtonItem \* right = \[\[UIBarButtonItem alloc\]initWithTitle:@"异步" style:UIBarButtonItemStylePlain target:self action:@selector(RhandelAction:)\];  
self.navigationItem.rightBarButtonItem = right;  
\[right release\];  

}
-(void)LhandelAction:(UIBarButtonItem *)sender{
//创建网址字符串
//method=album.channel.get&appKey=myKey&format=json&channel=t&pageNo=1&pageSize=10
NSString * str = [NSString stringWithFormat:KURL];
NSURL * Url = [NSURL URLWithString:str];
//创建请求对象
NSMutableURLRequest * request =[NSMutableURLRequest requestWithURL:Url];
//处理参数字符串
NSString * parmStr = [NSString stringWithFormat:@"method=album.channel.get&appKey=myKey&format=json&channel=t&pageNo=1&pageSize=10"];
//设置请求体。将参数字符串转化为NSData 对象
[request setHTTPBody:[parmStr dataUsingEncoding:NSUTF8StringEncoding]];
//设置请求方式
[request setHTTPMethod:@"POST"];//如果不设置的话,默认的为 get
//同步链接
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//解析
[self parseData:data];

}
-(void)parseData:data{
//系统 JSON 解析
NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options: error:nil];
NSLog(@"%@",dic);
}
//异步请求
-(void)RhandelAction:(UIBarButtonItem *)sender{

//创键网址字符串  
NSString \* str = \[NSString stringWithFormat:KURL\];  
//真实的网址对象  
NSURL \* URl = \[NSURL URLWithString:str\];  
//请求对象的创建  
NSMutableURLRequest \* request = \[NSMutableURLRequest requestWithURL:URl\];  
//处理参数部分  
NSString \* parmStr = \[NSString stringWithFormat:@"method=album.channel.get&appKey=myKey&format=json&channel=t&pageNo=1&pageSize=10"\];  
//设置请求体 将参数字符串转化为 NSData  
\[request setHTTPBody:\[parmStr dataUsingEncoding:NSUTF8StringEncoding\]\];  
//请求方式为 post  
\[request setHTTPMethod:@"POST"\];  
/\*  
//创建链接  
\[NSURLConnection sendAsynchronousRequest:request queue:\[NSOperationQueue mainQueue\] completionHandler:^(NSURLResponse \*response, NSData \*data, NSError \*connectionError) {  
    \[self parseData:data\];  
}\];  
 \*/  
//代理形式  
\[NSURLConnection connectionWithRequest:request delegate:self\];  

}

#pragma mark-----NSURLConnection 协议
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
self.dataSource = [NSMutableData data];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.dataSource appendData:data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
[self parseData:self.dataSource];
}

  • (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

#pragma mark - Table view data source

  • (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return ;
    }

  • (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return ;
    }

/*

  • (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];

    // Configure the cell…

    return cell;
    }
    */

/*
// Override to support conditional editing of the table view.

  • (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
    }
    */

/*
// Override to support editing the table view.

  • (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Delete the row from the data source
    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
    }
    */

/*
// Override to support rearranging the table view.

  • (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
    }
    */

/*
// Override to support conditional rearranging of the table view.

  • (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
    }
    */

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

  • (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    }
    */

@end

PostViewController文件

#pragma mark (Model.h文件)————————————————————————————————————————————————————

#import

@interface Model : NSObject
@property(nonatomic,retain)NSString * name ,* address ,* telephone;
-(instancetype)initWithDic:(NSDictionary *)dic;
@end

#pragma mark (.m文件)————————————————————————————————————————————————————

#import "Model.h"

@implementation Model
-(instancetype)initWithDic:(NSDictionary *)dic{
self = [super init];
if (self) {
[self setValuesForKeysWithDictionary:dic];
}
return self;
}
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{

}
@end

Model文件

#pragma mark (ImageViewController.h文件)————————————————————————————————————————————————————

#import

@interface ImageViewController : UIViewController
@property(nonatomic,retain)UIImageView * imageView;
@property(nonatomic,retain)UILabel * label;
@end

#pragma mark (.m文件)————————————————————————————————————————————————————

//
// ImageViewController.m
// NSURL_Request

#import "ImageViewController.h"

@interface ImageViewController ()
{
long long photoLength;//记录总数据的大小
}

@property(nonatomic,retain)UIImage * image;
@property(nonatomic,retain)NSMutableData * dataSource;

@end

@implementation ImageViewController
-(UIImage *)image{
if (!_image) {
self.image = [[UIImage alloc]init];
}
return _image;
}

  • (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpView];
    }

-(void)setUpView{
UIBarButtonItem * right = [[UIBarButtonItem alloc]initWithTitle:@"开始" style:UIBarButtonItemStylePlain target:self action:@selector(handleAction:)];
self.navigationItem.rightBarButtonItem = right;
[right release];

self.imageView = \[\[UIImageView alloc\]initWithFrame:\[\[UIScreen  mainScreen\] bounds\]\];  
 \[self.view addSubview:\_imageView\];

self.label = \[\[UILabel alloc\]initWithFrame:CGRectMake(, , self.view.frame.size.width - , )\];  
\[self.view addSubview:\_label\];  
\_label.backgroundColor = \[UIColor grayColor\];  
\[\_label release\];

}  

//异步请求
-(void)handleAction:(UIBarButtonItem *)sender{
// self.imageView = [[UIImageView alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
// NSString * str = @"http://img.zcool.cn/community/0332de1559f800a32f875370ac09559.jpg";
// NSURL * URL = [NSURL URLWithString:str];
// NSData * data = [NSData dataWithContentsOfURL:URL];
// UIImage * image = [UIImage imageWithData:data];
// self.imageView.image = image;
//
// [self.view addSubview:self.imageView];
// [_imageView release];

//创建网址对象  
NSURL \* URL = \[NSURL URLWithString:@"http://img.zcool.cn/community/0332de1559f800a32f875370ac09559.jpg"\];  

//创建 NSURLRequiret 请求对象
//cachePolicy 缓存策略
// timeoutInterval 请求超时时间
NSURLRequest * request = [[NSURLRequest alloc]initWithURL:URL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:];
//*********异步链接第二种方式————Block 方式

//第二种方式  
 \[NSURLConnection connectionWithRequest:request delegate:self\];  
//解析数据  

//
}

-(void)parserData:data{
//系统的解析数据
}
//收到数据响应的时候
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
self.dataSource = [NSMutableData data];
//response 包含服务器返回的数据的大小 类型
photoLength = response.expectedContentLength;//数据的总的大小
NSLog(@"数据的总的大小 %lld",photoLength);
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
//为了得到完整的数据,数据需要拼接
[self.dataSource appendData:data];
//求\ 已下载的数据的大小 / 总的数据的大小
NSUInteger persent = self.dataSource.length*1.0/photoLength;
NSLog(@"下载的比例 %f",(double)(unsigned long)persent);
self.label.text = [NSString stringWithFormat:@"%lu",(unsigned long)persent];
self.imageView.image = [UIImage imageWithData:self.dataSource];

}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
// [self parserData:self.dataSource];
}

  • (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

  • (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    }
    */

@end

ImageViewController文件