UI:網絡請求

JSON 外層是一個數組或者字典json

富文本(相對來講比較安全)、超文本,https安全超文本協議api

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(不可以看到請求的內容) 併發

區別app

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;
View Code 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
View Code 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:1];
    }
    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 1;
}

- (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
View Code 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: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.
}

#pragma mark - Table view data source

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

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

/*
- (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
View Code 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
View Code 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(10, 100, self.view.frame.size.width - 20, 100)];
    [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:10];
    //*********異步連接第二種方式————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
View Code ImageViewController文件
相關文章
相關標籤/搜索