时下流行的AFNNetworking 3.0框架使用简单,方便。对其进行第二次封装,使用起来更简单方便
#import
<Foundation/Foundation.h>
@interface
AFNManger :
NSObject
+(
AFNManger
*)shareAFNManger;
/** @brief GET
请求
*/
- (
void
)GET:(
NSString
*)URLString parameters:(
id
)parameters success:(
void
(^)(
id
data))success failure:(
void
(^)(
NSError
*error)) failure;
/** @brief POST
请求
*/
- (
void
)POST:(
NSString
*)URLString parameters:(
id
)parameters success:(
void
(^)(
id
data))success failure:(
void
(^)(
NSError
*error)) failure;
@end
#import
"AFNManger.h"
@implementation
AFNManger
static
AFNManger
*afnManger =
nil
;
//
单例
+ (
AFNManger
*)shareAFNManger
{
static
dispatch_once_t
onceToken;
dispatch_once
(&onceToken, ^{
if
(
afnManger
==
nil
) {
afnManger
= [[
self
alloc
]
init
];
}
});
return
afnManger
;
}
/**
*
获取
AFHTTPSessionManager
*/
- (
AFHTTPSessionManager
*)getHttpSessionManager
{
//
创建网络请求管理对象
AFHTTPSessionManager
*manager = [
AFHTTPSessionManager
manager
];
//
申明返回的结果是
json
类型
manager.
responseSerializer
= [
AFJSONResponseSerializer
serializer
];
//
申明请求的数据是
json
类型
manager.
requestSerializer
= [
AFJSONRequestSerializer
serializer
];
//
如果报接受类型不一致请替换一致
text/html
或别的
manager.
responseSerializer
.
acceptableContentTypes
= [
NSSet
setWithObjects
:
@"application/json"
,
@"text/json"
,
@"text/javascript"
,
@"text/html"
,
@"text/plain"
,
nil
];
return
manager;
}
/** @brief GET
请求
*/
- (
void
)GET:(
NSString
*)URLString parameters:(
id
)parameters success:(
void
(^)(
id
data))success failure:(
void
(^)(
NSError
*error)) failure{
//
创建网络请求管理对象
AFHTTPSessionManager
*manager = [
self
getHttpSessionManager
];
//
发送网络请求
(
请求方式为
GET)
[manager
GET
:URLString
parameters
:parameters
progress
:^(
NSProgress
*
_Nonnull
downloadProgress) {
}
success
:^(
NSURLSessionDataTask
*
_Nonnull
task,
id
_Nullable
responseObject) {
if
(success) {
success(responseObject);
}
}
failure
:^(
NSURLSessionDataTask
*
_Nullable
task,
NSError
*
_Nonnull
error) {
if
(failure) {
failure(error);
}
}];
}
- (
void
)POST:(
NSString
*)URLString parameters:(
id
)parameters success:(
void
(^)(
id
data))success failure:(
void
(^)(
NSError
*error)) failure{
//
创建网络请求管理对象
AFHTTPSessionManager
*manager = [
self
getHttpSessionManager
];
//
发送网络请求
(
请求方式为
POST)
[manager
POST
:URLString
parameters
:parameters
progress
:^(
NSProgress
*
_Nonnull
uploadProgress) {
}
success
:^(
NSURLSessionDataTask
*
_Nonnull
task,
id
_Nullable
responseObject) {
if
(success) {
success(responseObject);
}
}
failure
:^(
NSURLSessionDataTask
*
_Nullable
task,
NSError
*
_Nonnull
error) {
if
(failure) {
failure(error);
}
}];
}
@end