網絡請求的三層架構

  以person 爲例 下載人物圖片 信息

創建一個person 對象

  

 在.m 文件實現  

NSCopying,NSCoding 的協議

創建一個personList 管理person 對象



實現裏面的方法 其實可以把list 當做數組 來管理 person 對象  

 所以 重寫了數組的一些基本方法;


然後我們再創建一個 db 類 管理list 




創建db 是要管理list  所以從新寫下上面的方法。可以更好的調用list 裏面的方法;

基本上 數據模型已經出來了 我們要下載數據 還缺少一個 請求的一個類。

所以我們創建一個  httpHttpReques類


 實現方法

  http 請求方法;


#import "HttpReques.h"


@implementation HttpReques

-(void)creatWithString:(NSString *)urlStr withView:(NSInteger)viewId

{

    self.viewId = viewId;

    //定義URL

    NSURL *url = [NSURL URLWithString:urlStr];

    //創建網絡請求

    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

    //創建連接

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    //開始連接

    [connection start];

    self.data = [[NSMutableData alloc] init];

}

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

{

    UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"警告" message:@"error" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];

    [al show];

}

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

{

    [self.data appendData:data];

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    //把下載完成的數據 傳個引擎

//    NSDictionary * personDic = [NSJSONSerialization JSONObjectWithData:_data options:NSJSONReadingAllowFragments error:nil];

//

//    

//    NSArray *arr =[personDic objectForKey:@"data"];

    

    [self.dataDelegate ReloadData:_data withView:_viewId];

}

  從代碼 可以看出 我是把 下載完的數據 用代理傳給db;
  所以 需要2個協議
一個 下載數據 完成後給db
另一個  db處理完了數據 傳個 控制器

在控制器 只需要 寫三行代碼 就可以實現下載

 db =[[PersonDB alloc] init];

    db.TableDelegate =self;

       [db downLoadWithString:@"http://api.mengxiang.org/mxshow.php?mod=top&do=week" withView:110];


 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章