码迷,mamicode.com
首页 > 其他好文 > 详细

封装的一个GET和POST的异步方法

时间:2015-10-05 20:49:28      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

// h 里面写的

#import <Foundation/Foundation.h>

typedef void(^Myblock)(id object);

@interface NetworkHandle : NSObject



+ (void)getDataWithURLString:(NSString *)string compare:(Myblock)block;


+ (void)postDataWithURLString:(NSString *)string
                andBodyString:(NSString *)bodyString
                      compare:(Myblock)block;
@end

//m里面写的

#import "NetworkHandle.h"
@interface NetworkHandle ()
@property (nonatomic, strong) NSMutableData *data;
@end

@implementation NetworkHandle

+ (void)getDataWithURLString:(NSString *)string compare:(Myblock)block{

     //对地址做一次UTF-8的转码,防止参数里面有中文
    NSString *urlStr = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //将地址转换成url格式
    NSURL *url = [NSURL URLWithString:urlStr];
    //设置请求方式
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"];
     //同步还是异步
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data != nil) {
             //因为不确定数据的类型,所以用id泛型指针去接收
            id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            block(object);
        }
        
    }];

}


+ (void)postDataWithURLString:(NSString *)string andBodyString:(NSString *)bodyString compare:(Myblock)block{

    NSString *urlStr = [string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSString *parStr = bodyString;
    NSData *patData = [parStr dataUsingEncoding:NSUTF8StringEncoding];
    
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:patData];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data != nil) {
            id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            block(object);
        }
        
    }];
    
}

 

封装的一个GET和POST的异步方法

标签:

原文地址:http://www.cnblogs.com/mawenqiang/p/4856182.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!