.h文件声明方法
#import<Foundation/Foundation.h>
@interface ZHTTPManager : NSObject<NSURLConnectionDataDelegate,NSURLConnectionDelegate>
+ (void)startAsynchourRequestWithUrlString:(NSString *)URLString
params:(NSDictionary *)params
completionHandler:(void(^)(BOOL sucess,id content))completion;
@end
.m文件实现
#import"ZHTTPManager.h"
@interfaceZHTTPManager()
{
NSMutableData *_responseData;
void(^_completionHandler)(BOOL success,id content);
}
- (void)startAsynchourRequestWithUrlString:(NSString *)URLString params:(NSDictionary *)params completionHandler:(void (^)(BOOL, id))completion;
@property (copy,nonatomic) void (^completionHandler)(BOOL success,id content);
@end
@implementation ZHTTPManager
- (id)init
{
self = [super init];
if (self)
{
_responseData = [[NSMutableDataalloc]init];
}
returnself;
}
- (void)startAsynchourRequestWithUrlString:(NSString *)URLString params:(NSDictionary *)params completionHandler:(void (^)(BOOL, id))completion
{
self.completionHandler = completion;
NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:[NSURLURLWithString:URLString]];
request.HTTPMethod = @"POST";
request.timeoutInterval = 10.0;
NSMutableString *postString = [NSMutableStringstringWithFormat:@"g=ApiGGC"];
for (NSString *key in params)
{
[postString appendFormat:@"&%@=%@",key,[params objectForKey:key]];
}
request.HTTPBody = [postString dataUsingEncoding:NSUTF8StringEncoding];
[NSURLConnectionconnectionWithRequest:request delegate:self];
}
+ (void)startAsynchourRequestWithUrlString:(NSString *)URLString params:(NSDictionary *)params completionHandler:(void (^)(BOOL, id))completion
{
if (URLString.length == 0)
{
return;
}
ZHTTPManager *manager = [[[ZHTTPManager alloc]init] autorelease];;
[manager startAsynchourRequestWithUrlString:URLString params:params completionHandler:(void (^)(BOOL, id))completion];
}
+ (id)JSONObjectWithData:(NSData *)data
{
if (!data)
{
return nil;
}
NSError *error = nil;
id object = [NSJSONSerializationJSONObjectWithData:data
options:NSJSONReadingMutableLeaves
error:&error];
if (error)
{
NSLog(@"errormessage%@",[error localizedDescription]);
}
return object;
}
#pragmamark - <NSURLConnectionDataDelegate,NSURLConnectionDelegate>
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[_responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *dict = [ZHTTPManagerJSONObjectWithData:_responseData];
BOOL sucess = [dict[@"code"] integerValue] == 1 ? YES : NO;
_completionHandler(sucess,dict[@"content"]);
_responseData.length = 0;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
_completionHandler(NO,[error localizedDescription]);
}
@end
在其他controller导入可直接调用此方法,