我用一个单例类将一些常用的网络请求进行了二次封装,主要包括post请求 get请求  图片文件上传下载  视频的断点续传等功能。

首先大家先去github上下载AFN,将文件夹内的AFNetworking文件夹拖入工程中,然后创建一个图片文件参数类代码如下:

#import <Foundation/Foundation.h>

@interface UploadParam : NSObject
/**
* 上传文件的二进制数据
*/
@property (nonatomic, strong) NSData *data;
/**
* 上传的参数名称
*/
@property (nonatomic, copy) NSString *name;
/**
* 上传到服务器的文件名称
*/
@property (nonatomic, copy) NSString *fileName; /**
* 上传文件的类型
*/
@property (nonatomic, copy) NSString *mimeType; @end
#import "UploadParam.h"

@implementation UploadParam

@end

然后创建网络工具AFNManager具体代码如下(此处我提供了代理和block两种方式进行传值供大家选择):

#import <Foundation/Foundation.h>
#import "AFNManagerDelegate.h"
#import "UploadParam.h"
@interface AFNManager : NSObject @property (nonatomic, weak) id<AFNManagerDelegate> delegate; /**
* AFNManager单利
*/
+(AFNManager *)sharedManager;
#pragma mark --代理的方式传值
/**
* get
*/
- (void)GET:(NSString *)URLString parameters:(id)parameters; /**
* post
*/
- (void)Post:(NSString *)URLString parameters:(id)parameters; /**
* upload
*/
- (void)Upload:(NSString *)URLString parameters:(id)parameters uploadParam:(UploadParam *)uploadParam; #pragma mark --block的形式传值
/**
* get请求
*/
- (void)GET:(NSString *)URLString parameters:(id)parameters succeed:(void (^)(id data))succeed failure:(void (^)(NSError *error))failure;
/**
* post请求
*/
- (void)Post:(NSString *)URLString parameters:(id)parameters succeed:(void (^)(id data))succeed failure:(void (^)(NSError *error))failure;
/**
* upload
*/
- (void)Upload:(NSString *)URLString parameters:(id)parameters uploadParam:(UploadParam *)uploadParam succeed:(void (^)(id data))succeed failure:(void (^)(NSError *error))failure; #pragma mark --断点续传
/**
* 开始下载 断点续传
*
* @param URLString 请求接口
*/
- (void)downloadStartWithUrl:(NSString *)URLString fileName:(NSString *)fileName;
/**
* 开始上传 断点续传
*
* @param URLString 请求接口
*/
- (void)uploadStartWithUrl:(NSString *)URLString fileData:(NSData *)fileData;
/**
* 暂停操作 断点续传
*/
- (void)operationPause;
/**
* 继续操作 断点续传
*/
- (void)operationResume;
/**
* 取消操作
*/
- (void)operationCancel;
@end
#import "AFNManager.h"
#import "AFNetworking.h"
@interface AFNManager()
{
AFHTTPRequestOperation *operation; //创建请求管理(用于上传和下载)
}
@end
static AFNManager *manager = nil;
@implementation AFNManager
+(AFNManager *)sharedManager
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (manager == nil) {
manager = [[self alloc] init];
}
});
return manager;
} +(instancetype)allocWithZone:(struct _NSZone *)zone
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (manager == nil) { manager = [super allocWithZone:zone];
}
});
return manager;
}
- (void)GET:(NSString *)URLString parameters:(id)parameters
{
// 创建请求管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; [mgr GET:URLString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { if (self.delegate && [self.delegate respondsToSelector:@selector(AFNManagerDidSuccess:)]) { [self.delegate AFNManagerDidSuccess:responseObject];
} } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (self.delegate && [self.delegate respondsToSelector:@selector(AFNManagerDidFaild:)]) { [self.delegate AFNManagerDidFaild:error];
}
}];
} - (void)Post:(NSString *)URLString parameters:(id)parameters
{
// 创建请求管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; [mgr POST:URLString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { if (self.delegate && [self.delegate respondsToSelector:@selector(AFNManagerDidSuccess:)]) { [self.delegate AFNManagerDidSuccess:responseObject];
} } failure:^(AFHTTPRequestOperation *operation, NSError *error) { if (self.delegate && [self.delegate respondsToSelector:@selector(AFNManagerDidFaild:)]) { [self.delegate AFNManagerDidFaild:error];
}
}];
} - (void)Upload:(NSString *)URLString parameters:(id)parameters uploadParam:(UploadParam *)uploadParam
{
// 创建请求管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; [mgr POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { // 上传的文件全部拼接到formData /**
* FileData:要上传的文件的二进制数据
* name:上传参数名称
* fileName:上传到服务器的文件名称
* mimeType:文件类型
*/
[formData appendPartWithFileData:uploadParam.data name:uploadParam.name fileName:uploadParam.fileName mimeType:uploadParam.mimeType]; } success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (self.delegate && [self.delegate respondsToSelector:@selector(AFNManagerDidSuccess:)]) { [self.delegate AFNManagerDidSuccess:responseObject];
} } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (self.delegate && [self.delegate respondsToSelector:@selector(AFNManagerDidFaild:)]) { [self.delegate AFNManagerDidFaild:error];
}
}]; }
-(void)GET:(NSString *)URLString parameters:(id)parameters succeed:(void (^)(id))succeed failure:(void (^)(NSError *))failure
{
// 创建请求管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; [mgr GET:URLString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (responseObject == nil) {
return ;
}
succeed(responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { failure(error);
}];
}
-(void)Post:(NSString *)URLString parameters:(id)parameters succeed:(void (^)(id))succeed failure:(void (^)(NSError *))failure
{
// 创建请求管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; [mgr POST:URLString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (responseObject == nil) {
return ;
}
succeed(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { failure(error);
}]; }
-(void)Upload:(NSString *)URLString parameters:(id)parameters uploadParam:(UploadParam *)uploadParam succeed:(void (^)(id))succeed failure:(void (^)(NSError *))failure
{
// 创建请求管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; [mgr POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { // 上传的文件全部拼接到formData /**
* FileData:要上传的文件的二进制数据
* name:上传参数名称
* fileName:上传到服务器的文件名称
* mimeType:文件类型
*/
[formData appendPartWithFileData:uploadParam.data name:uploadParam.name fileName:uploadParam.fileName mimeType:uploadParam.mimeType]; } success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (self.delegate && [self.delegate respondsToSelector:@selector(AFNManagerDidSuccess:)]) { succeed(responseObject);
} } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (self.delegate && [self.delegate respondsToSelector:@selector(AFNManagerDidFaild:)]) { failure(error);
}
}]; }
-(void)downloadStartWithUrl:(NSString *)URLString fileName:(NSString *)fileName
{
NSString *filePath = [NSString stringWithFormat:@"%@/Documents/%@",NSHomeDirectory(), fileName]; operation = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:URLString]]]; operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
// 可以在此设置进度条 // [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
//
// }];
__weak typeof(self) weakself = self;
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// 请求成功做出提示
if (weakself.delegate && [weakself.delegate respondsToSelector:@selector(AFNManagerDidSuccess:)]) { [weakself.delegate AFNManagerDidSuccess:responseObject];
} } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 请求失败做出提示
if (weakself.delegate && [weakself.delegate respondsToSelector:@selector(AFNManagerDidFaild:)]) { [weakself.delegate AFNManagerDidFaild:error];
}
}]; [operation start];
}
- (void)uploadStartWithUrl:(NSString *)URLString fileData:(NSData *)fileData
{
operation = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:URLString]]]; operation.inputStream = [[NSInputStream alloc] initWithData:fileData]; // 设置进度条
// [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
//
// }];
__weak typeof(self) weakself = self;
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// 请求成功做出提示
if (weakself.delegate && [weakself.delegate respondsToSelector:@selector(AFNManagerDidSuccess:)]) { [weakself.delegate AFNManagerDidSuccess:responseObject];
} } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 请求失败做出提示
if (weakself.delegate && [weakself.delegate respondsToSelector:@selector(AFNManagerDidFaild:)]) { [weakself.delegate AFNManagerDidFaild:error];
}
}]; [operation start];
}
- (void)operationPause
{
[operation pause];
}
- (void)operationResume
{
[operation resume];
}
- (void)operationCancel
{
[operation cancel];
} //网络监听(用于检测网络是否可以链接。此方法最好放于AppDelegate中,可以使程序打开便开始检测网络)
- (void)reachabilityManager
{
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
//打开网络监听
[mgr.reachabilityManager startMonitoring]; //监听网络变化
[mgr.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) { //当网络不可用(无网络或请求延时)
case AFNetworkReachabilityStatusNotReachable:
break; //当为手机WiFi时
case AFNetworkReachabilityStatusReachableViaWiFi:
break; //当为手机蜂窝数据网
case AFNetworkReachabilityStatusReachableViaWWAN:
break; //其它情况
default:
break;
}
}]; // //停止网络监听(若需要一直检测网络状态,可以不停止,使其一直运行)
// [mgr.reachabilityManager stopMonitoring];
} @end

网络工具代理协议代码如下:

#import <Foundation/Foundation.h>
@class AFNManager; @protocol AFNManagerDelegate <NSObject> @optional
/**
* 发送请求成功
*
* @param manager AFNManager
*/
-(void)AFNManagerDidSuccess:(id)data;
/**
* 发送请求失败
*
* @param manager AFNManager
*/
-(void)AFNManagerDidFaild:(NSError *)error;
@end

有很多不足之处请大家多多指正,可以评论或点关注进行技术交流。后续也会写一些自己平时学习的点点滴滴。

iOS菜鸟之AFN的二次封装的更多相关文章

  1. iOS菜鸟之FMDB的二次封装简单易用

    闲来无事写点东西,希望大家多多指正! 大家先去git下载FMDB,然后将其中source文件夹中的fmdb文件夹拖入自己的项目中.最后就可以引用下面的代码对fmdb进行一次简单的封装. 这样可以更直观 ...

  2. swift4.0 对 afn 进行二次封装

    先将  afn 用pod导入到 工程中 创建一个类 ZHttpTools 继承自 AFHTTPSessionManager 一般我们不希望网络请求同时有多个存在,所以我们将这个工具类  设计成单例 代 ...

  3. 对AFN的二次封装

     .h .m

  4. AFN的二次封装

    http://www.cnblogs.com/sxwangjiadong/p/4970751.html

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

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

  6. ios MBProgressHUD 使用,及二次封装

    MBProgressHUD是一个显示HUD窗口的第三方类库,用于在执行一些后台任务时,在程序中显示一个表示进度的loading视图和两个可选的文本提示的HUD窗口.MBProgressHUD 二次封装 ...

  7. 对百度WebUploader开源上传控件的二次封装,精简前端代码(两句代码搞定上传)

    前言 首先声明一下,我这个是对WebUploader开源上传控件的二次封装,底层还是WebUploader实现的,只是为了更简洁的使用他而已. 下面先介绍一下WebUploader 简介: WebUp ...

  8. iOS开发之微信聊天工具栏的封装

    之前山寨了一个新浪微博(iOS开发之山寨版新浪微博小结),这几天就山寨个微信吧.之前已经把微信的视图结构简单的拖了一下(IOS开发之微信山寨版),今天就开始给微信加上具体的实现功能,那么就先从微信的聊 ...

  9. iOS开发UI篇—核心动画(UIView封装动画)

    iOS开发UI篇—核心动画(UIView封装动画) 一.UIView动画(首尾) 1.简单说明 UIKit直接将动画集成到UIView类中,当内部的一些属性发生改变时,UIView将为这些改变提供动画 ...

随机推荐

  1. python的相对路径导入问题

    用python做项目,如果项目大了,或者想更好的管理程序,总是要使用包.包解决了命名冲突的问题. 今天在使用python的相对路径导入的时候,遇到了不少的问题. 包导入情形: src/    __in ...

  2. Hadoop上结合opencv\javacv

    mac上安装opencv 1. 去 http://opencv.org 下载最新版OpenCV for Linux/Mac源文件,目前版本是2.4.3.下载后解压.2. 去 http://www.cm ...

  3. 在ubuntu14.04 64位中使用jd-gui

    使用时提示缺少库,输入命令sudo apt-get install libgtk2.0-0:i386 libxxf86vm1:i386 libsm6:i386 lib32stdc++6 参考:http ...

  4. Hibernate(五)一对一单向关联映射

    上次的博文中 Hibernate从入门到精通(四)基本映射我们已经讲解了一下基本映射和相关概念,接下来 我们会讲稍微复杂点的映射——关系映射. 关系映射分类 关系映射即在基本映射的基础上处理 多个相关 ...

  5. HDOJ 2012 素数判定

    Problem Description 对于表达式n^2+n+41,当n在(x,y)范围内取整数值时(包括x,y)(-39<=x < y<=50),判定该表达式的值是否都为素数. I ...

  6. 获得当前屏幕的CGRect

    CGRect mainScreen = [[UIScreen mainScreen] bounds];

  7. ACM1024动态规划

    #include <cstdio> #include <algorithm> #define FI(a, b, c) for(int a = (b); a <= (c); ...

  8. SVN 资源库报错 E175002

    遇到一个问题, svn: E175002: OPTIONS request failed on '/' Connection timed out: connect 试了网上好多办法,都没有,最后公司大 ...

  9. shared pool详解

    共享池shared pool的概念用户提交的命令:解析.执行用户命令的解析解析的过程是一个相当复杂的过程,它要考虑各种可能的异常情况比如SQL语句涉及到的对象不存在.提交的用户没有权限等等而且还需要考 ...

  10. JavaScript实现简单的打印功能

    var printSetup = function(){ // 打印页面设置 wb.execwb(8,1); }; var printPreView = function(){ // 打印页面预览 w ...