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 <UIKit/UIKit.h>

@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 <UIKit/UIKit.h>

@interface GetViewController : UITableViewController

@end

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

//
// GetViewController.m
// NSURL_Request #import "GetViewController.h"
#import "Model.h" @interface GetViewController ()<NSURLConnectionDataDelegate>
@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 <UIKit/UIKit.h>

@interface PostViewController : UITableViewController

@end

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

//
// PostViewController.m #define KURL @"http://api.tudou.com/v3/gw" #import "PostViewController.h" @interface PostViewController ()<NSURLConnectionDataDelegate>
@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 <Foundation/Foundation.h>

@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 <UIKit/UIKit.h>

@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 ()<NSURLConnectionDataDelegate>
{
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文件

UI:网络请求的更多相关文章

  1. 网络请求怎么样和UI线程交互? Activity2怎么通知Activity1 更新数据

    1.网络请求怎么样和UI线程交互? 目前我的做法是,建立线程池管理网络请求线程,通过添加task来新增网络请求.所有的网络操作通过统一的request来实现,网络返回结果通过回调onError和onS ...

  2. Android之三种网络请求解析数据(最佳案例)

    AsyncTask解析数据 AsyncTask主要用来更新UI线程,比较耗时的操作可以在AsyncTask中使用. AsyncTask是个抽象类,使用时需要继承这个类,然后调用execute()方法. ...

  3. 阶段一:通过网络请求,获得并解析JSON数据(天气应用)

    “阶段一”是指我第一次系统地学习Android开发.这主要是对我的学习过程作个记录. 在上一篇阶段一:解析JSON中提到,最近在写一个很简单的天气预报应用.即使功能很简单,但我还是想把它做成一个相对完 ...

  4. iOS开发——post异步网络请求封装

    IOS中有许多网络请求的函数,同步的,异步的,通过delegate异步回调的. 在做一个项目的时候,上网看了很多别人的例子,发现都没有一个简单的,方便的异步请求的封装例子.我这里要给出的封装代码,是异 ...

  5. ReactiveCocoa代码实践之-RAC网络请求重构

    前言 RAC相比以往的开发模式主要有以下优点:提供了统一的消息传递机制:提供了多种奇妙且高效的信号操作方法:配合MVVM设计模式和RAC宏绑定减少多端依赖. RAC的理论知识非常深厚,包含有FRP,高 ...

  6. android 网络请求Ⅰ

    本章讲述在android开发中,常用的网络请求操作.网络请求利用android基本的HttpURLConnection连接URL和开源网络请求包AsyncHttpClient.本次网络请求以调取天气接 ...

  7. 使用Fiddler针对Android手机网络请求抓包

    本文转载自大牛Trinea的博文:Android利用Fiddler进行网络数据抓包 主要介绍Android及IPhone手机上如何利用Fiddler进行网络数据抓包,比如我们想抓某个应用(微博.微信. ...

  8. 浅论Android网络请求库——android-async-http

    在iOS开发中有大名鼎鼎的ASIHttpRequest库,用来处理网络请求操作,今天要介绍的是一个在Android上同样强大的网络请求库android-async-http,目前非常火的应用Insta ...

  9. 【Android】Volley做网络请求的几种用法

    前言: 最近在将自己写的烂代码重构,以前使用的网络请求全是基于apache的HttpClient,简单使用还好,使用多了发现重复代码太多,而且每次使用都很繁琐,因此在网上找了半天网络请求的相关类库,最 ...

随机推荐

  1. hdu 3879 最大密集子图(点和边均带权)(模板)

    /* 最大权闭合图,可以用最大密集子图来解速度更快复杂度低 题解:胡伯涛<最小割模型在信息学竞赛中的应用> 点和边均带权的最大密集子图 s-i,权为U=点权绝对值和+边的所有权值 i-t, ...

  2. bzoj4568 [Scoi2016]幸运数字 线性基+树链剖分

    A 国共有 n 座城市,这些城市由 n-1 条道路相连,使得任意两座城市可以互达,且路径唯一.每座城市都有一个 幸运数字,以纪念碑的形式矗立在这座城市的正中心,作为城市的象征.一些旅行者希望游览 A ...

  3. 搭建双塔(vijos 1037)

    描述 2001年9月11日,一场突发的灾难将纽约世界贸易中心大厦夷为平地,Mr. F曾亲眼目睹了这次灾难.为了纪念“9?11”事件,Mr. F决定自己用水晶来搭建一座双塔. Mr. F有N块水晶,每块 ...

  4. iOS url带中文下载时 报错解决方法

    问题描述:下载文件时, 请求带中文的URL的资源时,比如:http://s237.sznews.com/pic/2010/11/23/e4fa5794926548ac953a8a525a23b6f2/ ...

  5. why在重写equals时还必须重写hashcode方法

    首先我们先来看下String类的源码:可以发现String是重写了Object类的equals方法的,并且也重写了hashcode方法 public boolean equals(Object anO ...

  6. HttpUtils 用于进行网络请求的工具类

    原文:http://www.open-open.com/code/view/1437537162631 import java.io.BufferedReader; import java.io.By ...

  7. C#编程语言及.NET 平台快速入门指南

    github: https://github.com/mfjiang e-mail: hamlet.jiang@live.com   ⼀.C#,CLR,IL,JIT概念 以及 .NET 家族 (⼀)基 ...

  8. 一句话从MySQL导出CSV文件

    mysql -h <host> -u<user> -p<passport> crm -e "select ....." | csvcut -t ...

  9. 再谈用java实现Smtp发送邮件之Socket编程

    很多其它内容欢迎訪问个人站点   http://icodeyou.com 前几天利用Socket实现了用java语言搭建webserver,全程下来应该会对Socket这个东西已经使用的很熟悉了.尽管 ...

  10. kindle】扫描版PDF完美切割六寸

    kindle]扫描版PDF完美切割六寸  半夏 2013-11-05 18:36:01     软件来源记不清了..连使用说明的网址都找不到了,自己写一下使用方法大家凑合一下呗~    软件是大牛写的 ...