iOS简单封装网络请求,使用block回掉函数方式

//
//  RequestHttpClass.h
//  封装简单的异步请求

#import <Foundation/Foundation.h>

// 相当于定义一个函数指针
typedef void(^FinishLoadBlock)(NSData *);

@interface RequestHttpClass : NSMutableURLRequest <NSURLConnectionDataDelegate>

// 存储异步请求的数据
@property (nonatomic, retain) NSMutableData *data;
@property (nonatomic, retain) NSURLConnection *connection;
@property (nonatomic, copy)FinishLoadBlock block;

- (void)startAsync;
- (void)cancel;
@end


//
//  RequestHttpClass.m
//  RequestClass
//
//  Copyright (c) 2013年 TestApp. All rights reserved.
//

#import "RequestHttpClass.h"

@implementation RequestHttpClass

-(void)startAsync {
    self.data = [[NSMutableData alloc] init];
    
     // 发起异步请求
    self.connection = [NSURLConnection connectionWithRequest:self delegate:self];
    
}

- (void)cancel {
    [self.connection cancel];
}

// 异步请求每次返回的数据
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.data appendData:data];
}

// 异步请求结束数据返回
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
    self.block(_data);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"请求网络出错:%@", error);
}

-(void) dealloc {
    [_data release];
    [super dealloc];
}

//
//  RequestData.h
//  RequestClass
//
//  Copyright (c) 2013年 TestApp. All rights reserved.
//

#import <Foundation/Foundation.h>

typedef void(^Completion)(id);

@interface RequestData : NSObject

// 访问天气预报接口
+ (void)getWeatherData:(NSDictionary *)params block: (Completion) block;

@end


//
//  RequestData.m
//  RequestClass
//
//  Created by 王德康 on 13-10-2.
//  Copyright (c) 2013年 TestApp. All rights reserved.
//

#import "RequestData.h"
#import "RequestHttpClass.h"

#define BASE_URL @"http://www.weather.com.cn/data/sk/"

@implementation RequestData

+ (void)getWeatherData:(NSDictionary *)params block:(Completion )block {
    
    NSString *cityCode = [params objectForKey:@"code"];
    NSString *urlstring = [BASE_URL stringByAppendingFormat:@"%@.html",cityCode];
    
    RequestHttpClass *request = [RequestHttpClass requestWithURL:[NSURL URLWithString:urlstring]];
    [request setHTTPMethod:@"GET"];
    [request setTimeoutInterval:60];
    
    request.block = ^(NSData *data) {
        id ret = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        block(ret);
    };
    
    [request startAsync];
}
@end

你可能感兴趣的:(网络请求封装)