異步POST請求及加載信息到UitabView上


有一個New類,有三個屬性name(title),summary和newsUrl;JSON解析的是一個字典套數組套字典的形式。


{
    "news": [
        {
            "rownum": 1, 
            "id": "B664817CFB08FCE", 
            "title": "京郊避暑遊達到峯值  週末農家客棧不預定住不上", 
            "type": "北京新聞", 
            "cid": "213", 
            "cname": "北京新聞", 
            "newsUrl": "http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/Site_PV_Count.ashx?newsId=B664817CFB08FCE&createDate=20140727&PID=213&UpdateTime=1406459313", 
            "typeId": "01", 
            "sequence": 1, 
            "attribute": 0, 
            "lastUpdateTime": "1406459313", 
            "PUBLISHDATE": "20140727", 
            "picUrl": "http://ipad-bjwb.bjd.com.cn/DigitalPublication/MediaLibrary/20140727/B664817CFB08FCE/80755750BBA178D8.jpg", 
            "summary": " 2014年7月27日  北京 進入三伏天,北京周邊的河畔和山谷就成了許多市民週末納涼的去處。這個週末,高達35℃的天氣又將不少城裏人“趕”到京郊去,不少出京路段甚至出現了擁堵。昨天一大早,京承路往密雲、懷柔去的方向就從四環一直堵到了六環,這其中,不少是到京郊納涼避暑的市民。“我們8點出發,本以爲不晚,誰知道已經開始堵了。”昨天市民劉先生帶着全家老少出行,在京承路足足堵了兩個多小時,車行緩慢。“現在訂房得排到8月底了”霧靈山腳下的新城子村宋曉梅家的農家客棧住宿已經爆滿,這裏既有市民全家出遊,也有不少企業組織員工到京郊避暑。由於人多,客棧廚師人手短缺,已經從村裏臨時借了兩個廚工幫忙。院主告訴記者,進入暑期已經不分週末還是工作日了,幾乎天天客滿,週六、日人更多,如果不提前預定,這一帶都找不到住宿。“今年水量並不大,可是遊客還是比預計的要多。”京北第一漂景區昨天一天就涌進了2000多遊客。雖然今年的水量很少,並不是玩漂流最好的時候,但還是有不少遊客願意到水中嬉戲。“山裏的溫度平均比城裏低5℃,早晚更涼快,住在這裏晚上還要蓋薄被。”延慶珍珠泉村的農家院昨天也全部擠滿了城裏避暑的市民,有不少市", 
            "commentCount": 0
        }, 


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        // Custom initialization

        

        

        self.arr = [NSMutableArray array];

        

        // 1. 建立請求

        

        // 獲取文件路徑

        NSURL *url = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];

        

        // 建立請求對象

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];

        

        // 設定請求的方式

        request.HTTPMethod = @"POST";

        

        // 設定POST請求的Body

        

        // 需要提交的表單

        NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";

        

        // bodyStr轉爲NSData

        NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];

        

        // 設置請求的bodyNSData類型)

        request.HTTPBody = bodyData;

        

        

        

        // 2.異步連接服務器 Block回調

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

            

            // 將結果轉爲字符串

            NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

            NSLog(@"-----%@", result);

            

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

            

            NSMutableArray *array = [dic objectForKey:@"news"];

            // 遍歷數組

            for (NSDictionary *dictionary in array) {

                News *new = [[News alloc] initWithNSDictionary:dictionary];

                [self.arr addObject:new];

                // 重新加載數據

                [self.tableView reloadData];

                [new release];

            }

        }];

        

    }

    return self;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];

    self.tableView.separatorColor = [UIColor purpleColor];

    self.tableView.delegate = self;

    self.tableView.dataSource = self;

    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"1"];

    [self.view addSubview:self.tableView];

    [_tableView release];

}


// New類對象的個數

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return [self.arr count];

}


// cell裏的內容爲title

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"1"];

    cell.textLabel.text = [[self.arr objectAtIndex:indexPath.row] name];

    return cell;

}


// 推出下一個頁面,將New類對象傳過去

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    SecondViewController *second = [[SecondViewController alloc] init];

    second.newObject = [self.arr objectAtIndex:indexPath.row];

    [self.navigationController pushViewController:second animated:YES];

    [second release];

}




secondViewController.m

- (void)viewDidLoad

{

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    

    

    // 接收MainViewController傳來的New對象

    UITextView *textView = [[UITextView alloc] initWithFrame:self.view.bounds];

    textView.text = self.newObject.summary;

    textView.editable = NO;

    [self.view addSubview:textView];

    [textView release];

    

    // webView的顯示

    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 320, 320, 160)];

    // 路徑是newsUrl 是一個字符串, 將它進行加載

    NSURL *url = [NSURL URLWithString:self.newObject.newsUrl];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];

    // 加載請求

    [webView loadRequest:request];

    [self.view addSubview:webView];

    [webView release];

}



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