第一層 HMRequest 功能
- HTTP 常用請(qǐng)求方式 GET POST PUT PATCH DELETE
- POST 上傳JSON數(shù)據(jù)
- PHOTO 單張多張照片上傳
HMRequest.h
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
@interface HMRequestModel : HMBaseModel
@property (nonatomic, strong) NSNumber *code;
@property (nonatomic, copy) NSString *message;
@end
typedef void(^HMRequestSuccessBlock)(id result, HMRequestModel *model);
typedef void(^HMRequestFailureBlock)(NSString *msg);
typedef NS_ENUM(NSInteger, HMRequestMethod) {
HTTP_REQUEST_TYPE_GET = 0,
HTTP_REQUEST_TYPE_POST = 1,
HTTP_REQUEST_TYPE_PUT = 2,
HTTP_REQUEST_TYPE_PATCH = 3,
HTTP_REQUEST_TYPE_DELETE = 4,
};
typedef NS_ENUM(NSInteger, HMRequestStatus) {
HTTP_REQUEST_STATUS_FAILURE = -1,
HTTP_REQUEST_STATUS_SUCCESS = 0
};
@interface HMRequest : NSObject
#pragma mark- http request
+ (void)hm_requestActionWithUrl:(NSString *)url
params:(NSDictionary *)params
method:(HMRequestMethod)method
success:(HMRequestSuccessBlock)success
failure:(HMRequestFailureBlock)failure;
#pragma mark- json request
+ (void)hm_postJsonDataWithUrl:(NSString *)url
params:(NSDictionary *)params
success:(HMRequestSuccessBlock)success
failure:(HMRequestFailureBlock)failure;
#pragma mark- photo request
+ (void)hm_upLoadPhotoWithUrl:(NSString *)url
params:(NSDictionary *)params
photoSize:(CGSize)photoSize
photos:(NSArray *)photos
success:(HMRequestSuccessBlock)success
failure:(HMRequestFailureBlock)failure;
@end
HMRequest.m
#import "HMRequest.h"
@implementation HMRequestModel
@end
@implementation HMRequest
+ (void)hm_requestActionWithUrl:(NSString *)url
params:(NSDictionary *)params
method:(HMRequestMethod)method
success:(HMRequestSuccessBlock)success
failure:(HMRequestFailureBlock)failure
{
// [HMServerConfig HMServerAddress] 為正式/測(cè)試環(huán)境前綴可自行處理
NSString *requestUrl = HM_FORMAT_TWO(@"%@%@", [HMServerConfig HMServerAddress], url);
requestUrl = [requestUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
if (method == HTTP_REQUEST_TYPE_GET) {
[[HMRequest manager] GET:requestUrl
parameters:params
progress:nil
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
HMRequestModel *model = [HMRequestModel yy_modelWithDictionary:responseObject];
if ([model.code integerValue] == HTTP_REQUEST_STATUS_SUCCESS) success(responseObject, model);
if ([model.code integerValue] == HTTP_REQUEST_STATUS_FAILURE) success(nil, model);
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure([HMRequest errorInfo:error]);
}];
}
if (method == HTTP_REQUEST_TYPE_POST) {
[[HMRequest manager] POST:requestUrl
parameters:params progress:nil
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
HMRequestModel *model = [HMRequestModel yy_modelWithDictionary:responseObject];
if ([model.code integerValue] == HTTP_REQUEST_STATUS_SUCCESS) success(responseObject, model);
if ([model.code integerValue] == HTTP_REQUEST_STATUS_FAILURE) success(nil, model);
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure([HMRequest errorInfo:error]);
}];
}
if (method == HTTP_REQUEST_TYPE_PUT) {
[[HMRequest manager] PUT:requestUrl
parameters:params
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
HMRequestModel *model = [HMRequestModel yy_modelWithDictionary:responseObject];
if ([model.code integerValue] == HTTP_REQUEST_STATUS_SUCCESS) success(responseObject, model);
if ([model.code integerValue] == HTTP_REQUEST_STATUS_FAILURE) success(nil, model);
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure([HMRequest errorInfo:error]);
}];
}
if (method == HTTP_REQUEST_TYPE_PATCH) {
[[HMRequest manager] PATCH:requestUrl
parameters:params
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
HMRequestModel *model = [HMRequestModel yy_modelWithDictionary:responseObject];
if ([model.code integerValue] == HTTP_REQUEST_STATUS_SUCCESS) success(responseObject, model);
if ([model.code integerValue] == HTTP_REQUEST_STATUS_FAILURE) success(nil, model);
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure([HMRequest errorInfo:error]);
}];
}
if (method == HTTP_REQUEST_TYPE_DELETE) {
[[HMRequest manager] DELETE:requestUrl
parameters:params
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
HMRequestModel *model = [HMRequestModel yy_modelWithDictionary:responseObject];
if ([model.code integerValue] == HTTP_REQUEST_STATUS_SUCCESS) success(responseObject, model);
if ([model.code integerValue] == HTTP_REQUEST_STATUS_FAILURE) success(nil, model);
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure([HMRequest errorInfo:error]);
}];
}
}
+ (void)hm_postJsonDataWithUrl:(NSString *)url
params:(NSDictionary *)params
success:(HMRequestSuccessBlock)success
failure:(HMRequestFailureBlock)failure
{
NSString *requestUrl = HM_FORMAT_TWO(@"%@%@", [HMServerConfig HMServerAddress], url);
requestUrl = [requestUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:requestUrl parameters:nil error:nil];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (responseObject) {
HMRequestModel *model = [HMRequestModel yy_modelWithDictionary:responseObject];
if ([model.code integerValue] == HTTP_REQUEST_STATUS_SUCCESS) success(responseObject, model);
if ([model.code integerValue] == HTTP_REQUEST_STATUS_FAILURE) success(nil, model);
} else {
failure([HMRequest errorInfo:error]);
}
}] resume];
}
+ (void)hm_upLoadPhotoWithUrl:(NSString *)url
params:(NSDictionary *)params
photoSize:(CGSize)photoSize
photos:(NSArray *)photos
success:(HMRequestSuccessBlock)success
failure:(HMRequestFailureBlock)failure
{
NSString *requestUrl = HM_FORMAT_TWO(@"%@%@", [HMServerConfig HMServerAddress], url);
requestUrl = [requestUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSLog(@"url:%@\nparams:%@", requestUrl, params);
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[SVProgressHUD show];
[manager POST:requestUrl parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
for (int i = 0; i < photos.count; i++) {
NSData *imageData = UIImageJPEGRepresentation(photos[i], 0.6f);
NSLog(@"upload image size: %ld k", (long)(imageData.length / 1024));
NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *imageName = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.jpg",imageName];
[formData appendPartWithFileData:imageData name:@"image" fileName:fileName mimeType:@"image/jpeg"];
}
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
HMRequestModel *model = [HMRequestModel yy_modelWithDictionary:responseObject];
if ([model.code integerValue] == HTTP_REQUEST_STATUS_SUCCESS) success(responseObject, model);
if ([model.code integerValue] == HTTP_REQUEST_STATUS_FAILURE) success(nil, model);
NSLog(@"responseObject:%@", responseObject);
[SVProgressHUD dismiss];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure([HMRequest errorInfo:error]);
}];
}
+ (NSString *)errorInfo:(NSError *)error
{
return error.userInfo[@"message"] ? error.userInfo[@"message"] : @"網(wǎng)絡(luò)斷開連接,請(qǐng)稍后再試";
}
+ (AFHTTPSessionManager *)manager
{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html",
@"text/css",
@"text/json",
@"text/javascript",
@"text/plain",
@"application/json",
@"application/x-javascript",
@"application/javascript",
@"application/vnd.api+json", nil]];
return manager;
}
@end
第二層 HMService 功能
- 按模塊進(jìn)行category類別劃分(例如HMNetService、HMNetService+mine)
HMService.h
#import "HMNetService.h"
@interface HMNetService (mine)
// 個(gè)人信息 -> 上傳照片
+ (void)upLoadWithPhotos:(NSArray *)photos
type:(NSNumber *)type
complete:(MultiActionBlock)complete;
@end
HMService.m
#import "HMNetService+mine.h"
static NSString * const upLoadImageUrl = @"/upload/image";
@implementation HMNetService (mine)
+ (void)upLoadWithPhotos:(NSArray *)photos
type:(NSNumber *)type
complete:(MultiActionBlock)complete
{
HMParams *params = [HMParams new];
[params addParam:@"type" value:type];
[HMRequest hm_upLoadPhotoWithUrl:upLoadImageUrl
params:params.params
photoSize:CGSizeMake(50, 50)
photos:photos
success:^(id result, HMRequestModel *model) {
complete(result, model, model.message);
} failure:^(NSString *msg) {
complete(nil, nil, msg);
}];
}
第三層 外部調(diào)用實(shí)現(xiàn)功能
- block回調(diào)鸭你,非常簡(jiǎn)潔只關(guān)注最后結(jié)果做處理
[HMNetService upLoadWithPhotos:@[photo]
type:@(type)
complete:^(NSDictionary *result, HMRequestModel *requestModel, NSString *message) {
if (result) {
// 成功處理
} else {
// 失敗處理
}
[[iToast makeText:message] show];
}];