对iOS网络请求的简单封装,并且使用block回调函数方式

// 废话不多说直接上代码

 

//     RequestHttpClass.h文件  

/*封装简单的异步请求*/

#import


// 相当于定一个函数指

typedef void(^FinishLoadBlock)(NSData *);


@interface RequestHttpClass : NSMutableURLRequest


// 异步求的数据

@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

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

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