// 废话不多说直接上代码
// RequestHttpClass.h文件
/*封装简单的异步请求*/
#import <Foundation/Foundation.h>
// 相当于定义一个函数指针
typedef void(^FinishLoadBlock)(NSData *);
@interface RequestHttpClass : NSMutableURLRequest <NSURLConnectionDataDele
// 存储异步请求的数据
@property (nonatomic, retain) NSMutableData *data;
@property (nonatomic, retain) NSURLConnection *connection;
@property (nonatomic, copy)FinishLoadBlock block;
- (void)startAsync;
- (void)cancel;
@end
// RequestHttpClass.m 文件
#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)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"请求网络出错:%@", error);
}
-(void) dealloc {
[_data release];
[super dealloc];
}
@end
-------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
// RequestData.h 文件
#import <Foundation/Foundation.h>
typedef void(^Completion)(id);
@interface RequestData : NSObject
// 访问天气预报接口
+ (void)getWeatherData:(NSDictionary *)params block: (Completion) block;
@end
// RequestData.m 文件
#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_URLstringByAppendingFormat:@"%@.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