.h 中
#import <Foundation/Foundation.h>
typedef void(^Sucess)(id responseData);
typedef void(^Failure)(NSError *error);
@interface NetWorkManager : NSObject
+ (instancetype)sharedInstance;
/**
* 发送get请求
*
* @param URLString 请求的网址字符串
* @param parameters 请求的参数
* @param success 请求成功的回调
* @param failure 请求失败的回调
*/
- (void)getWithURLString:(NSString *)URLString success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure;
/**
* 发送post请求
*
* @param URLString 请求的网址字符串
* @param parameters 请求的参数
* @param success 请求成功的回调
* @param failure 请求失败的回调
*/
- (void)postWithURLString:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(id responseObject))success
failure:(void (^)(NSError *error))failure;
@end
.m 中
#import "NetWorkManager.h"
#import <AFNetworking.h>
@implementation NetWorkManager
static id _instance = nil;
+ (instancetype)sharedInstance {
return [[self alloc] init];
}
#pragma mark -- GET请求 --
- (void)getWithURLString:(NSString *)URLString
success:(void (^)(id))success
failure:(void (^)(NSError *))failure {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html", nil];
manager.requestSerializer.timeoutInterval = 30;
[manager GET:URLString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure(error);
}
}];
}
#pragma mark -- POST请求 --
- (void)postWithURLString:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(id))success
failure:(void (^)(NSError *))failure {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html", nil];
[manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure(error);
}
}];
}
Viewcontroller 中调用
// get 请求, post 类似
[[NetWorkManager sharedInstance]getWithURLString:@"geturl" success:^(id responseObject) {
NSLog(@"地方舒服舒服 = %@",responseObject);
} failure:^(NSError *error) {
}];
网友评论