iOS菜鸟之AFN的二次封装
我用一个单例类将一些常用的网络请求进行了二次封装,主要包括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的二次封装的更多相关文章
- iOS菜鸟之FMDB的二次封装简单易用
闲来无事写点东西,希望大家多多指正! 大家先去git下载FMDB,然后将其中source文件夹中的fmdb文件夹拖入自己的项目中.最后就可以引用下面的代码对fmdb进行一次简单的封装. 这样可以更直观 ...
- swift4.0 对 afn 进行二次封装
先将 afn 用pod导入到 工程中 创建一个类 ZHttpTools 继承自 AFHTTPSessionManager 一般我们不希望网络请求同时有多个存在,所以我们将这个工具类 设计成单例 代 ...
- 对AFN的二次封装
.h .m
- AFN的二次封装
http://www.cnblogs.com/sxwangjiadong/p/4970751.html
- iOS项目相关@AFN&SDWeb的二次封装
一,AFNetworking跟SDWebImge是功能强大且常用的第三方,然而在实际应用中需要封装用来复用今天就跟大家分享一下AFN&SDWeb的二次封装 1. HttpClient.h及.m ...
- ios MBProgressHUD 使用,及二次封装
MBProgressHUD是一个显示HUD窗口的第三方类库,用于在执行一些后台任务时,在程序中显示一个表示进度的loading视图和两个可选的文本提示的HUD窗口.MBProgressHUD 二次封装 ...
- 对百度WebUploader开源上传控件的二次封装,精简前端代码(两句代码搞定上传)
前言 首先声明一下,我这个是对WebUploader开源上传控件的二次封装,底层还是WebUploader实现的,只是为了更简洁的使用他而已. 下面先介绍一下WebUploader 简介: WebUp ...
- iOS开发之微信聊天工具栏的封装
之前山寨了一个新浪微博(iOS开发之山寨版新浪微博小结),这几天就山寨个微信吧.之前已经把微信的视图结构简单的拖了一下(IOS开发之微信山寨版),今天就开始给微信加上具体的实现功能,那么就先从微信的聊 ...
- iOS开发UI篇—核心动画(UIView封装动画)
iOS开发UI篇—核心动画(UIView封装动画) 一.UIView动画(首尾) 1.简单说明 UIKit直接将动画集成到UIView类中,当内部的一些属性发生改变时,UIView将为这些改变提供动画 ...
随机推荐
- Android开源项目发现--- 传感器篇(持续更新)
Great Android Sensing Toolkit Android感应器工具包,包含示例及使用过程中可能需要的算法 项目地址:https://github.com/gast-lib/gast- ...
- 【HDOJ】2782 The Worm Turns
DFS. /* 2782 */ #include <iostream> #include <queue> #include <cstdio> #include &l ...
- 查找IP来源
通过调用淘宝IP库获取IP归属地,脚本如下: #!/usr/bin/env python # -*- coding: utf-8 -*- import urllib import json impor ...
- 《University Calculus》-chape5-积分法-积分的定义
这一章节讨论积分的定义以及微积分基本定理. 笔者先前在数学证明专栏中关于高斯定理的证明的开头,给出了一段关于微积分思想的概括,文中提到根据导数(微分)的定义,根据其逆定义来给出积分的定义和计算方法,这 ...
- HDU2037 今年暑假不AC 贪心算法
贪心算法 : 贪心算法就是只考虑眼前最优解而忽略整体的算法, 它所做出的仅是在某种意义上的局部最优解, 然后通过迭代的方法相继求出整体最优解. 但是不是所有问题都可以得到整体最优解, 所以选择贪心策略 ...
- Validate XML using a XSD (XML Schema)
Consider this XML file howto.xml : <?xml version="1.0" encoding="ISO-8859-1"? ...
- Codeforces Round #100(140~~)
140 A. New Year Table 题目大意:有一个大圆桌子,半径是R, 然后有n个半径是r的盘子,现在需要把这些盘子摆放在桌子上,并且只能摆放在桌子边缘,但是不能超出桌子的范围....问能放 ...
- C# 操作配置文件
1.配置文件app.config的书写: string mdbPath = ConfigurationManager.AppSettings["mdbPath"].ToString ...
- first blog编程之美-----计算1的个数
根据以下总结写出以下程序,总结来源于网上 感想:得硬着头皮找规律 #include int count1(int n) { int i=1; int count=0 ...
- mysql in查询 结果乱序 引发的思考
Mysql in查询 结果集 乱序 SQL: select * from table where id IN (3,6,9,1,2,5,8,7); 这样的情况取出来后,其实,id还是按1,2,3,4, ...