一个用来放接口的文件夹:
代码的模块区分要清晰:
代码注释必须清晰(不管是.h还是.m文件):
.h文件:
#pragma mark - 用户登录接口
/**
用户登录接口
@param phoneNumber 电话号码
@param smsCode 短信验证码
@param success 登录成功的回调
@param failure 登录失败的回调
*/
+ (void)userLoginWithPhoneNumber:(NSString *)phoneNumber smsCode:(NSString *)smsCode success:(void(^)(NSDictionary *responseDict))success failure:(void(^)(NSString *errormessage))failure;
.m文件:
#pragma mark - 用户登录接口
/**
用户登录接口
@param phoneNumber 电话号码
@param smsCode 短信验证码
@param success 登录成功的回调
@param failure 登录失败的回调
*/
+ (void)userLoginWithPhoneNumber:(NSString *)phoneNumber smsCode:(NSString *)smsCode success:(void (^)(NSDictionary *))success failure:(void (^)(NSString *))failure{
//------- URL -------//
NSString *url = [BASE_URL stringByAppendingPathComponent:@"user/login"];
//------- 参数 -------//
NSMutableDictionary *paraDict = [NSMutableDictionary dictionary];
[paraDict setObject:phoneNumber forKey:@"mobile"];
[paraDict setObject:smsCode forKey:@"sms_code"];
//------- 请求 -------//
[AFHTTPSessionManager requestWithType:AFHTTPSessionManagerRequestTypePost URLString:url parameters:paraDict success:^(NSURLSessionDataTask *task, id responseObject) {
success(responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
failure(error.localizedDescription);
}];
}
调用自己封装的接口:
[APIManagement getOrderListWithUid:[User sharedSingleton].uid orderStatus:orderStatus page:_page limit:20 success:^(NSDictionary *responseDict) {
if ([responseDict[@"result"]boolValue] == true) {
NSMutableArray *orderArray = responseDict[@"data"][@"order_array"];
if (orderArray.count == 0) { // 如果订单数据为空
}else{
success(orderArray);
// 如果有更多数据
if ([responseDict[@"data"][@"has_more"] boolValue] == true) {
_page ++;
}
}
}else{
[UIAlertView alertWithMessage:responseDict[@"msg"]];
}
} failure:^(NSString *errormessage) {
}];
写了一个基于AFHTTPSessionManager
的具有get&post请求功能的category:
- .h文件
@interface AFHTTPSessionManager (Util)
typedef NS_ENUM(NSInteger, AFHTTPSessionManagerRequestType) {
AFHTTPSessionManagerRequestTypeGet = 1,
AFHTTPSessionManagerRequestTypePost = 2
};
+ (void)requestWithType:(AFHTTPSessionManagerRequestType)type
URLString:(NSString *)urlStr
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
@end
- .m文件
@implementation AFHTTPSessionManager (Util)
+ (void)requestWithType:(AFHTTPSessionManagerRequestType)type URLString:(NSString *)urlStr parameters:(id)parameters success:(void (^)(NSURLSessionDataTask * task, id responseObj))success failure:(void (^)(NSURLSessionDataTask * task, NSError * error))failure
{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json", nil];
// 设置请求头
[manager.requestSerializer setValue:[Management getUniqueDeviceID] forHTTPHeaderField:@"呵呵"];
if ([User sharedSingleton].token) {
[manager.requestSerializer setValue:[User sharedSingleton].token forHTTPHeaderField:@"哈哈"];
}
if (type == AFHTTPSessionManagerRequestTypeGet) {
[manager GET:urlStr parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
success(task,responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(task,error);
}];
}else if(type == AFHTTPSessionManagerRequestTypePost){
[manager POST:urlStr parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
success(task,responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(task,error);
}];
}
}
@end
这个category的使用,举例说明:
#pragma mark - 用户登录接口
/**
用户登录接口
@param phoneNumber 电话号码
@param smsCode 短信验证码
@param success 登录成功的回调
@param failure 登录失败的回调
*/
+ (void)userLoginWithPhoneNumber:(NSString *)phoneNumber smsCode:(NSString *)smsCode success:(void (^)(NSDictionary *))success failure:(void (^)(NSString *))failure{
//------- URL -------//
NSString *url = [BASE_URL stringByAppendingPathComponent:@"user/login"];
//------- 参数 -------//
NSMutableDictionary *paraDict = [NSMutableDictionary dictionary];
[paraDict setObject:phoneNumber forKey:@"mobile"];
[paraDict setObject:smsCode forKey:@"sms_code"];
//------- 请求 -------//
[AFHTTPSessionManager requestWithType:AFHTTPSessionManagerRequestTypePost URLString:url parameters:paraDict success:^(NSURLSessionDataTask *task, id responseObject) {
success(responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
failure(error.localizedDescription);
}];
}
最重要的,数据请求API文件必须好看,不好看就是败笔:
2018年1月23日更新
随着项目的不断变大,我感觉把所有接口放到一个类里太臃肿了。
为了避免这种现象,我现在的一个页面结构大概是这样的:
除了Model、View、Controller,还有个request,这个类负责这个页面的所有数据请求。
如上图的CQOrderListRequest
文件:
#import "CQOrderListRequest.h"
@implementation CQOrderListRequest
/**
获取订单列表
@param typeValue 类型
@param success 获取成功的回调
@param failure 获取失败的回调
*/
+ (void)getOrderListWithTypeValue:(NSString *)typeValue
success:(void (^)(NSDictionary *))success
failure:(void (^)(NSString *))failure {
//------- URL -------//
NSString *URL = [DOMAIN_NAME stringByAppendingPathComponent:@"我们不一样"];
//------- 参数 -------//
NSMutableDictionary *paraDict = [NSMutableDictionary dictionary];
paraDict[@"user_id"] = [UserManagement sharedManager].user_id;
paraDict[@"type"] = @"我们不一样";
paraDict[@"type_value"] = typeValue;
//------- 请求 -------//
[APIManagement GET:URL parameters:paraDict success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if ([responseObject[@"result"] boolValue] == true) {
success(responseObject[@"data"]);
} else {
failure(responseObject[@"msg"]);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(error.localizedDescription);
}];
}
@end
里面有个类:APIManagement
,这个类是对AFN的封装:
CQHTTPSessionManager.h
:
#import
@interface CQHTTPSessionManager : AFHTTPSessionManager
/** 单例 */
+ (instancetype)sharedManager;
+ (instancetype)alloc __attribute__((unavailable("call 'sharedManager' instead")));
+ (instancetype)new __attribute__((unavailable("call 'sharedManager' instead")));
- (instancetype)copy __attribute__((unavailable("call 'sharedManager' instead")));
- (instancetype)mutableCopy __attribute__((unavailable("call 'sharedManager' instead")));
@end
CQHTTPSessionManager.m
:
#import "CQHTTPSessionManager.h"
@implementation CQHTTPSessionManager
+ (instancetype)sharedManager {
static CQHTTPSessionManager *manager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (manager == nil) {
manager = [CQHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json", nil];
// 设置请求头,根据业务而定
[manager.requestSerializer setValue:@"xx" forHTTPHeaderField:@"xx"];
[manager.requestSerializer setValue:@"xx2" forHTTPHeaderField:@"xx2"];
}
});
return manager;
}
@end
APIManagement.m
#import "APIManagement.h"
#import "CQHTTPSessionManager.h"
@implementation APIManagement
/**
get请求
@param URLString URL
@param parameters 参数
@param success 请求成功的回调
@param failure 请求失败的回调
*/
+ (void)GET:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure {
[[CQHTTPSessionManager sharedManager] GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
success(task, responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(task, error);
}];
}
/**
post请求
@param URLString URL
@param parameters 参数
@param success 请求成功的回调
@param failure 请求失败的回调
*/
+ (void)POST:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure {
[[CQHTTPSessionManager sharedManager] POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
success(task, responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(task, error);
}];
}
@end
Demo
https://github.com/CaiWanFeng/APIManagement