文章标题

来源:互联网 发布:合并两个排序数组js 编辑:程序博客网 时间:2024/06/06 05:16

创建空文件夹

在.h中

typedef void(^BLOCK)(id result);

@interface NetworkHandler : NSObject

@property (nonatomic, copy) BLOCK passValue;

  • (void)getDataWithURLString:(NSString *)urlStr complention:(BLOCK)block;
  • (void)connectNetGetDataWithURLString:(NSString *)urlStr complention:(BLOCK)block;

  • (void)getDataWithURLString:(NSString )urlStr URLBodyString:(NSString )bodyStr complention:(BLOCK)block;

  • (void)connectNetGetDataWithURLString:(NSString )urlStr URLBodyString:(NSString )bodyStr complention:(BLOCK)block;

@end

.m中

@implementation NetworkHandler

  • (void)getDataWithURLString:(NSString *)urlStr complention:(BLOCK)block
    {
    [self setPassValue:block];
    NSString *str = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.f];
    [request setHTTPMethod:@”GET”];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if (data != nil) {
    id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

        [self passValue](object);    //            NSLog(@"%@", object);}

    }];
    }

  • (void)connectNetGetDataWithURLString:(NSString *)urlStr complention:(BLOCK)block
    {
    NetworkHandler *net = [[NetworkHandler alloc] init];
    [net getDataWithURLString:urlStr complention:block];
    // [net autorelease];
    }

  • (void)getDataWithURLString:(NSString )urlStr URLBodyString:(NSString )bodyStr complention:(BLOCK)block
    {
    [self setPassValue:block];

    NSString *str = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.f];

    [request setHTTPMethod:@”POST”];

    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];

    [request setHTTPBody:bodyData];

    // 连接
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if (data != nil) {
    id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

        [self passValue](object);}

    }];
    }

  • (void)connectNetGetDataWithURLString:(NSString )urlStr URLBodyString:(NSString )bodyStr complention:(BLOCK)block
    {
    NetworkHandler *net = [[NetworkHandler alloc] init];
    [net getDataWithURLString:urlStr URLBodyString:bodyStr complention:block];
    // [net autorelease];
    }

@end

0 0
原创粉丝点击