网络请求 下拉刷新 block传值

本文介绍了一个基于iOS平台的城市列表应用程序的实现过程。该应用通过网络请求获取国家和城市数据,并使用UITableView展示数据。同时,实现了数据的异步加载、刷新功能及简单的导航交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//
//  RootTableViewController.m
//  NetJSONCountry
//
//  Created by sunlihuo on 15/5/26.
//  Copyright (c) 2015年 sunlihuo. All rights reserved.
//

#import "RootTableViewController.h"
#import "Country.h"
#import "CityTableViewController.h"
#import "Common.h"

@interface RootTableViewController ()
@property (strong, nonatomic) NSMutableArray *countrys;
@property (strong, nonatomic) CityTableViewController *cityVC;

@end

@implementation RootTableViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.countrys = [NSMutableArray new];
        [self onCreate];
        
    }
    return self;
}

-(void)onCreate{
    NSURL *url = [NSURL URLWithString:kWeiboCountryURL];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError) {
            NSLog(@"error is %@", connectionError);
        } else {
            NSError *error = nil;
            NSArray *tmpArr = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
            //NSLog(@"tmpDict is %@", tmpArr);
            NSDictionary *tmpDict = nil;
            Country *country = nil;
            for (int i = 0; i < tmpArr.count; i++) {
                tmpDict = tmpArr[i];
                for (NSString *key in tmpDict.allKeys) {
                    country = [Country new];
                    country.countryID = key;
                    country.countryName = tmpDict[key];
                    [self.countrys addObject:country];
                }
            }
            //NSLog(@"self.countrys is %@", self.countrys);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        }
    }];
    

}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    UIBarButtonItem *reloadBtn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(reload:)];
    reloadBtn.title = @"刷新";
    [self.navigationItem setRightBarButtonItem:reloadBtn animated:YES];
    
}

-(void)reload:(UIBarButtonItem *)sender{
    [self onCreate];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //创建下拉刷新组件
    self.refreshControl = [[UIRefreshControl alloc]init];
    self.refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:@"松开刷新"];
    [self.refreshControl addTarget:self action:@selector(refreshTableView) forControlEvents:UIControlEventValueChanged];
    
    
}

#pragma mark 下拉刷新
-(void)refreshTableView{
    [self.refreshControl beginRefreshing];
    [self onCreate];
    [self.refreshControl endRefreshing];
}


- (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 {
    //NSLog(@"self.countrys.count is %zi", self.countrys.count);
    return self.countrys.count;
    
    //return 10;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellID = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
    }
    //NSLog(@"cell is %@", cell);
    Country *country = self.countrys[indexPath.row];
    cell.textLabel.text = country.countryName;
    cell.detailTextLabel.text = country.countryID;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    //NSLog(@"country.countryName is %@", country.countryName);
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!self.cityVC) {
        self.cityVC = [CityTableViewController new];
    }
    self.cityVC.title = [NSString stringWithFormat:@"%@城市列表",self.countrys[indexPath.row]];
    self.cityVC.country = self.countrys[indexPath.row];
    

    [self.cityVC initWithBlock:^(Country *country) {
        NSString *msg = [NSString stringWithFormat:@"您选择了%@", country];
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }];
    
    [self.navigationController pushViewController:self.cityVC animated:YES];
    
}

/*
// 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




//
//  CityTableViewController.h
//  NetJSONCountry
//
//  Created by sunlihuo on 15/5/26.
//  Copyright (c) 2015年 sunlihuo. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "Country.h"
#import "Country.h"

typedef void(^MyBlock)(Country *country);

@interface CityTableViewController : UITableViewController

@property (strong, nonatomic) Country *country;
@property (strong, nonatomic) MyBlock myBlock;

-(void)initWithBlock:(MyBlock)block;

@end



//
//  CityTableViewController.m
//  NetJSONCountry
//
//  Created by sunlihuo on 15/5/26.
//  Copyright (c) 2015年 sunlihuo. All rights reserved.
//

#import "CityTableViewController.h"
#import "RootTableViewController.h"
@interface CityTableViewController ()
@property (strong, nonatomic) NSMutableArray *citys;

@end

@implementation CityTableViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self onCreate];
    
}


-(void)onCreate{
    self.citys = [NSMutableArray new];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://api.weibo.com/2/common/get_province.json?access_token=2.00ZtlF5C0GvJSM28ba1329cb6CdARD&country=%@",self.country.countryID]];
    NSLog(@"%@", self.country.countryID);
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError) {
            NSLog(@"error is %@", connectionError);
        } else {
            NSError *error = nil;
            NSArray *tmpArr = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
            NSLog(@"tmpDict count is %zi", tmpArr.count);
            NSDictionary *tmpDict = nil;
            Country *country = nil;
            for (int i = 0; i < tmpArr.count; i++) {
                tmpDict = tmpArr[i];
                for (NSString *key in tmpDict.allKeys) {
                    country = [Country new];
                    country.countryID = key;
                    country.countryName = tmpDict[key];
                    [self.citys addObject:country];
                }
            }
            NSLog(@"self.citys is %@", self.citys);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        }
    }];
    
    
}


- (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.citys.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"**************************");
    NSString *cellID = @"cityCellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
    }
    //NSLog(@"cell is %@", cell);
    Country *country = self.citys[indexPath.row];
    cell.textLabel.text = country.countryName;
    cell.detailTextLabel.text = country.countryID;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    NSLog(@"country.countryName is %@", country.countryName);
    return cell;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.navigationController popViewControllerAnimated:YES];
    self.myBlock(self.citys[indexPath.row]);
}

-(void)initWithBlock:(MyBlock)block{
    self.myBlock = block;
}


/*
// 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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值