iOS项目相关@AFN&SDWeb的二次封装

时间:2021-11-09 15:43:23

一,AFNetworking跟SDWebImge是功能强大且常用的第三方,然而在实际应用中需要封装用来复用今天就跟大家分享一下AFN&SDWeb的二次封装

iOS项目相关@AFN&SDWeb的二次封装

1.

HttpClient.h及.m

.h定义了HTTP常用的四种GET POST PUT DELETE 请求

一般分别用做增删减查

定义前预处理,请求成功处理,请求失败处理的block

及带多参数w的方法声明

.m设置请求类型跟响应类型,监听网络是否有网络,如果没有,弹出网络异常的警示框

2.

UIImageView+WebCache.h及.m

这是类别的方法,把网络请求图片封装起来

.h 定义加载成功,加载失败及加载进度的block

下载未成功时预设图片的加载方法及网络请求下载图片的方法声明

.m

是两个方法的具体实现

 #import <Foundation/Foundation.h>
#import "AFNetworking.h" //HTTP请求类别
typedef NS_ENUM(NSInteger,HttpRequestType) {
HttpRequestGet,
HttpRequestPost,
HttpRequestPut,
HttpRequestDelete,
}; /**
* 请求前预处理block
*/
typedef void(^PrepareExecuteBlock)(void); typedef void(^SuccessBlock)(NSURLSessionDataTask * task, id responseObject); typedef void(^FailureBlock)(NSURLSessionDataTask * task, NSError * error); @interface HttpClient : NSObject + (HttpClient *)defaultClient; /**
* HTTP请求(GET,POST,PUT,DELETE)
*
* @param url 请求地址
* @param method 请求类型
* @param params 请求参数
* @param prepare 请求前预处理
* @param success 请求成功处理
* @param failure 请求失败处理
*/ - (void)requestWithPath:(NSString *)url
method:(NSInteger)method
paramenters:(NSDictionary *)params
prepareExecute:(PrepareExecuteBlock)prepare
success:(SuccessBlock)success
failure:(FailureBlock)failure; @end
 #import "HttpClient.h"

 @interface HttpClient ()

 @property (nonatomic, strong) AFHTTPSessionManager * manager;

 @property (nonatomic, assign) BOOL isConnect;

 @end

 @implementation HttpClient

 - (instancetype)init
{
self = [super init];
if (self) { self.manager = [AFHTTPSessionManager manager];
//设置请求类型
self.manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//设置响应类型
self.manager.responseSerializer = [AFJSONResponseSerializer serializer]; self.manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html", @"text/json", @"text/javascript",@"text/plain",@"image/gif", nil]; //开启监听
[self openNetMonitoring]; }
return self;
} - (void)openNetMonitoring { [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { switch (status) {
case AFNetworkReachabilityStatusUnknown:
self.isConnect = NO;
break;
case AFNetworkReachabilityStatusNotReachable:
self.isConnect = NO;
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
self.isConnect = YES;
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
self.isConnect = YES;
break;
default:
break;
} }]; [[AFNetworkReachabilityManager sharedManager] startMonitoring]; self.isConnect = YES;
} + (HttpClient *)defaultClient { static HttpClient * instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[self alloc] init];
});
return instance;
} - (void)requestWithPath:(NSString *)url
method:(NSInteger)method
paramenters:(NSDictionary *)params
prepareExecute:(PrepareExecuteBlock)prepare
success:(SuccessBlock)success
failure:(FailureBlock)failure { NSLog(@"请求网络地址为:%@",url); if ([self isConnectionAvailable]) { //预处理
if (prepare) {
prepare();
} switch (method) {
case HttpRequestGet:
[self.manager GET:url parameters:params progress:nil success:success failure:failure];
break;
case HttpRequestPost:
[self.manager POST:url parameters:params progress:nil success:success failure:failure];
break;
case HttpRequestPut:
[self.manager PUT:url parameters:params success:success failure:failure];
break;
case HttpRequestDelete:
[self.manager DELETE:url parameters:params success:success failure:failure];
break;
default:
break;
} } else { [self showExceptionDialog];
}
} - (BOOL)isConnectionAvailable { return self.isConnect;
} - (void)showExceptionDialog { [[[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接异常,请检查网络连接" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles: nil] show];
} @end
 #import <UIKit/UIKit.h>
#import "UIImageView+WebCache.h" typedef void (^DownloadSuccessBlock) (SDImageCacheType cacheType, UIImage *image);
typedef void (^DownloadFailureBlock) (NSError *error);
typedef void (^DownloadProgressBlock) (CGFloat progress); @interface UIImageView (SDWebImage) /**
* SDWebImage 下载并缓存图片
*
* @param url 图片的url
*
* @param place 还未下载成功时的替换图片
*
*/
- (void)downloadImage:(NSString *)url
place:(UIImage *)place; /**
* SDWebImage 下载并缓存图片和下载进度
*
* @param url 图片的url
*
* @param place 还未下载成功时的替换图片
*
* @param success 图片下载成功
*
* @param failure 图片下载失败
*
* @param progress 图片下载进度
*/
- (void)downloadImage:(NSString *)url
place:(UIImage *)place
success:(DownloadSuccessBlock)success
failure:(DownloadFailureBlock)failure
received:(DownloadProgressBlock)progress; @end
 #import "UIImageView+SDWebImage.h"

 @implementation UIImageView (SDWebImage)

 - (void)downloadImage:(NSString *)url
place:(UIImage *)place
{
[self sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:place options:SDWebImageLowPriority | SDWebImageRetryFailed];
} - (void)downloadImage:(NSString *)url
place:(UIImage *)place
success:(DownloadSuccessBlock)success
failure:(DownloadFailureBlock)failure
received:(DownloadProgressBlock)progress
{
[self sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:place options:SDWebImageRetryFailed | SDWebImageLowPriority progress:^(NSInteger receivedSize, NSInteger expectedSize) { progress((float)receivedSize/expectedSize); } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { if (error) {
failure(error);
}else{
// image是下载好的图片
self.image = image;
success(cacheType, image);
}
}];
} @end