利用block封装网络请求类

1.创建网络请求类NetRequest,头文件如下
typedef void(^BLOCK)(id result);

@interface NetRequest : NSObject
@property (nonatomic, copy) BLOCK bl;
- (void)requestNetWithUrl:(NSString *)urlStr BodyOfRequestForString:(NSString *)bodyStr block:(BLOCK)bl;
+ (void)PostWithUrl:(NSString *)urlStr BodyOfRequestForString:(NSString *)bodyStr block:(BLOCK)bl;
@end
解释:该处利用的是异步post传值,头文件写法基本上跟block传值一样,我这里写了一个+号方法,为的是能在使用NetRequest类的时候更加方便。可以看到这里的方法有三个参数,分别是url的地址,以及设置request的HttpBody属性的,这里属于网络请求,不做过多解释。 

2.下面看.m文件:实现俩个方法

- (void)requestNetWithUrl:(NSString *)urlStr BodyOfRequestForString:(NSString *)bodyStr block:(BLOCK)bl
{
  self.bl = bl;
  NSURL *url = [NSURL URLWithString:urlStr];
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
  request.HTTPMethod = @"post";
  NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
  request.HTTPBody = bodyData;
  [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
     NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options :NSJSONReadingMutableContainers error:nil];
    NSLog(@"%d", [[dic objectForKey:@"news"] count]);
    self.bl(dic);
    
}];
  
}
+ (void)PostWithUrl:(NSString *)urlStr BodyOfRequestForString:(NSString *)bodyStr block:(BLOCK)bl
{
  NetRequest *netRequest = [[NetRequest alloc] init];
  [netRequest requestNetWithUrl:urlStr BodyOfRequestForString:bodyStr block:bl];
}
解释:-方法中首先要设置属性block=参数block,再将要传的值添加到block方法的参数中。+号方法是利用-号方法将参数block传给属性block。因为在+号方法中不能直接给属性赋值。 

3.如何使用:将数据传输到ViewController上

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
  self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  if (self) {
    // Custom initialization
    self.array = [NSMutableArray array];
    self.title = @"新闻";
    NSString *urlStr = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
    NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
    [NetRequest PostWithUrl:urlStr BodyOfRequestForString:bodyStr block:^(id result) {
      self.array = [result objectForKey:@"news"];
      [self.tableView reloadData];
    }];
  }
  return self;
}

- (void)viewDidLoad
{
  [super viewDidLoad];
  // Do any additional setup after loading the view.
  self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 480) style:UITableViewStylePlain];
  [self.view addSubview:self.tableView];
  self.tableView.dataSource = self;
  self.tableView.delegate = self;
  [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuse"];
  
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  NSString *str = @"reuse";
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
  cell.textLabel.numberOfLines = 2;
  cell.textLabel.text = [[self.array objectAtIndex:indexPath.row] objectForKey:@"title"];
  return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  WebViewController *webVC = [[WebViewController alloc] init];
  webVC.webUrl = [[self.array objectAtIndex:indexPath.row] objectForKey:@"newsUrl"];
  [self.navigationController pushViewController:webVC animated:YES];
  [webVC release];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  return [self.array count];
}

下面来看看为什么我们要用这种传值方式:因为我要把当前获得的数据传输给一个UIViewController,而这个UIViewController上面有UITableView,需要刷新,而我们获取网络数据的时候使用的是利用block封装的一个获取NSData的方法,该方法会在数据加载完后才会执行块语句,而且网络会有延迟,我们的UI界面会优先于数据显示在手机上,所以当数据请求成功后,我们需要刷新页面,即调用UITableView的reloadData方法,所以才使用这种策略。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值