最新 AFNetworking 3.0 简单实用封装
AFNetworking 3.0 的到来使我们开发者又方便了许多,话不多说,直接上代码。
1.首先 引入框架AFNetworking框架
GitHub下载地址:https://github.com/AFNetworking/AFNetworking
AFNetworking官网地址:http://afnetworking.com
2.导入AFNetworking 支持框架
#import<MobileCoreServices/MobileCoreServices.h>
#import<SystemConfiguration/SystemConfiguration.h>
3.简单实用封装
AFNManagerDelegate.h
//
// AFNManagerDelegate.h
// WayCar
//
// Created by zhitu on 16/1/16.
// Copyright © 2016年 Eric. All rights reserved.
// #import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "AFNetworking.h" //AF 3.0 版本 #define BASE_URL @"http://xxx.xx.xx.174:80/AppFrameWork" #pragma mark 网络请求类型
enum HTTPMETHOD{ METHOD_GET = 0, //GET请求
METHOD_POST = 1, //POST请求
}; @interface AFNManagerRequest : NSObject /**
* 类方法
*/
+ (AFNManagerRequest *)sharedUtil; /**
* iOS自带网络请求框架
*/
+ (void)requestURL:(NSString *)urlstring
httpMethod:(NSString *)method
params:(NSMutableDictionary *)params
complection:(void(^)(id result))block; /**
* AF数据请求
*/
+(void)requestAFURL:(NSString *)URLString
httpMethod:(NSInteger)method
parameters:(id)parameters
succeed:(void (^)(id))succeed
failure:(void (^)(NSError *))failure; /**
* 上传单张图片
*/
+(void)requestAFURL:(NSString *)URLString
parameters:(id)parameters
imageData:(NSData *)imageData
succeed:(void (^)(id))succeed
failure:(void (^)(NSError *))failure; /**
* 上传多张图片
*/
+(void)requestAFURL:(NSString *)URLString
parameters:(id)parameters
imageDataArray:(NSArray *)imageDataArray
succeed:(void (^)(id))succeed
failure:(void (^)(NSError *))failure; /**
* 上传文件
*/
+(void)requestAFURL:(NSString *)URLString
parameters:(id)parameters
fileData:(NSData *)fileData
succeed:(void (^)(id))succeed
failure:(void (^)(NSError *))failure; /*json
* @brief 把格式化的JSON格式的字符串转换成字典
* @param jsonString JSON格式的字符串
* @return 返回字典
*/
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString; /*json
* @brief 把字典转换成字符串
* @param jsonString JSON格式的字符串
* @return 返回字符串
*/
+(NSString*)URLEncryOrDecryString:(NSDictionary *)paramDict IsHead:(BOOL)_type; @end
AFNManagerDelegate.m
//
// AFNManagerDelegate.m
// WayCar
//
// Created by zhitu on 16/1/16.
// Copyright © 2016年 Eric. All rights reserved.
// #import "AFNManagerRequest.h"
@interface AFNManagerRequest() @end @implementation AFNManagerRequest /**
* 类方法
*/
+ (AFNManagerRequest *)sharedUtil { static dispatch_once_t onceToken;
static AFNManagerRequest * setSharedInstance; dispatch_once(&onceToken, ^{
setSharedInstance = [[AFNManagerRequest alloc] init]; });
return setSharedInstance;
} /**
* iOS自带网络请求框架
*/
+ (void)requestURL:(NSString *)urlstring
httpMethod:(NSString *)method
params:(NSMutableDictionary *)params
complection:(void(^)(id result))block{ //1.构造URL
urlstring = [BASE_URL stringByAppendingString:urlstring];
NSURL *url = [NSURL URLWithString:urlstring]; //2.构造request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setTimeoutInterval:60];
[request setHTTPMethod:method]; //1>拼接请求参数:username=wxhl&password=123456&key=value&....
NSMutableString *paramsString = [NSMutableString string];
NSArray *allKeys = params.allKeys;
for (int i=0; i<params.count; i++) {
NSString *key = allKeys[i];
NSString *value = params[key]; [paramsString appendFormat:@"%@=%@",key,value]; if (i < params.count-1) {
[paramsString appendString:@"&"];
}
} //2>添加请求参数:
/*
请求参数的格式1: username=wxhl&password=123456&key=value&....
请求参数的格式2 JSON:{username:wxhl,password:12345,....}
*/
//将字典 ----> JSON字符串
//JSONKit
// NSString *jsonString = [params JSONString];
// NSLog(@"%@",jsonString); /**
* 判断请求方式:
GET : 参数拼接在URL后面
POST : 参数添加到请求体中
*/
if ([method isEqualToString:@"GET"]) { NSString *separe = url.query?@"&":@"?";
NSString *paramsURL = [NSString stringWithFormat:@"%@%@%@",urlstring,separe,paramsString]; request.URL = [NSURL URLWithString:paramsURL];
}
else if([method isEqualToString:@"POST"]) { NSData *bodyData = [paramsString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:bodyData];
} //3.构造连接对象
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { if (connectionError != nil) {
NSLog(@"网络请求失败 : %@",connectionError);
return ;
} //1.解析JSON
// JSON字符串 ---> 字典、数组
id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; //2.回到主线程
dispatch_sync(dispatch_get_main_queue(), ^{ //回调block
block(result); });
}];
} /**
* AF网络请求
*/
+(void)requestAFURL:(NSString *)URLString
httpMethod:(NSInteger)method
parameters:(id)parameters
succeed:(void (^)(id))succeed
failure:(void (^)(NSError *))failure
{
// 0.设置API地址
URLString = [NSString stringWithFormat:@"%@%@",BASE_URL,[URLString stringByReplacingOccurrencesOfString:@" " withString:@"%20"]];
DNSLog(@"\n AF网络请求参数列表:%@\n\n 接口名: %@\n\n",parameters,URLString); // 1.创建请求管理者
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; // 2.申明返回的结果是二进制类型
manager.responseSerializer = [AFHTTPResponseSerializer serializer]; // 3.如果报接受类型不一致请替换一致text/html 或者 text/plain
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil]; // 4.请求超时,时间设置
manager.requestSerializer.timeoutInterval = 30; // 5.选择请求方式 GET 或 POST
switch (method) {
case METHOD_GET:
{
[manager GET:URLString parameters:nil progress:nil success:^(NSURLSessionDataTask *task, id responseObject) { NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; succeed([AFNManagerRequest dictionaryWithJsonString:responseStr]); DNSLog(@"\n 请求成功:%@\n\n",[AFNManagerRequest dictionaryWithJsonString:responseStr]); } failure:^(NSURLSessionDataTask *task, NSError *error) { failure(error); DNSLog(@"\n 请求失败:%@\n\n",error);
}];
}
break; case METHOD_POST:
{
[manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) { NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; succeed([AFNManagerRequest dictionaryWithJsonString:responseStr]); DNSLog(@"\n 请求成功:%@\n\n",[AFNManagerRequest dictionaryWithJsonString:responseStr]); } failure:^(NSURLSessionDataTask *task, NSError *error) { [LCProgressHUD showFailure:@"加载失败"]; failure(error); DNSLog(@"\n 请求失败:%@\n\n",error); }];
}
break; default:
break;
}
} /**
* 上传单张图片
*/
+(void)requestAFURL:(NSString *)URLString
parameters:(id)parameters
imageData:(NSData *)imageData
succeed:(void (^)(id))succeed
failure:(void (^)(NSError *))failure
{
// 0.设置API地址
URLString = [NSString stringWithFormat:@"%@%@",BASE_URL,[URLString stringByReplacingOccurrencesOfString:@" " withString:@"%20"]];
DNSLog(@"\n POST上传单张图片参数列表:%@\n\n%@\n",parameters,[AFNManagerRequest URLEncryOrDecryString:parameters IsHead:false]); // 1.创建请求管理者
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; // 2.申明返回的结果是二进制类型
manager.responseSerializer = [AFHTTPResponseSerializer serializer]; // 3.如果报接受类型不一致请替换一致text/html 或者 text/plain
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil]; // 4.请求超时,时间设置
manager.requestSerializer.timeoutInterval = 30; // 5. POST数据
[manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { // 在网络开发中,上传文件时,是文件不允许被覆盖,文件重名
// 要解决此问题,
// 可以在上传时使用当前的系统事件作为文件名
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmss"; // 设置时间格式
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.png", str]; //将得到的二进制图片拼接到表单中 /** data,指定上传的二进制流;name,服务器端所需参数名*/
[formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/png"]; }progress:nil success:^(NSURLSessionDataTask *task, id responseObject) { NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; succeed([AFNManagerRequest dictionaryWithJsonString:responseStr]); } failure:^(NSURLSessionDataTask *task, NSError *error) { failure(error);
}];
} /**
* 上传多张图片
*/
+(void)requestAFURL:(NSString *)URLString
parameters:(id)parameters
imageDataArray:(NSArray *)imageDataArray
succeed:(void (^)(id))succeed
failure:(void (^)(NSError *))failure
{
// 0.设置API地址
URLString = [NSString stringWithFormat:@"%@%@",BASE_URL,[URLString stringByReplacingOccurrencesOfString:@" " withString:@"%20"]];
DNSLog(@"\n POST上传多张图片参数列表:%@\n\n%@\n",parameters,[AFNManagerRequest URLEncryOrDecryString:parameters IsHead:false]); // 1.创建请求管理者
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; // 2.申明返回的结果是二进制类型
manager.responseSerializer = [AFHTTPResponseSerializer serializer]; // 3.如果报接受类型不一致请替换一致text/html 或者 text/plain
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil]; // 4.请求超时,时间设置
manager.requestSerializer.timeoutInterval = 30; // 5. POST数据
[manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { for (int i = 0; i<imageDataArray.count; i++){ NSData *imageData = imageDataArray[i]; // 在网络开发中,上传文件时,是文件不允许被覆盖,文件重名
// 要解决此问题,
// 可以在上传时使用当前的系统事件作为文件名
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 设置时间格式
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
NSString *name = [NSString stringWithFormat:@"image_%d.png",i ]; //将得到的二进制图片拼接到表单中 /** data,指定上传的二进制流;name,服务器端所需参数名*/
[formData appendPartWithFileData:imageData name:name fileName:fileName mimeType:@"image/png"];
} }progress:nil success:^(NSURLSessionDataTask *task, id responseObject) { NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; succeed([AFNManagerRequest dictionaryWithJsonString:responseStr]); } failure:^(NSURLSessionDataTask *task, NSError *error) { failure(error);
}];
} /**
* 上传文件
*/
+(void)requestAFURL:(NSString *)URLString
parameters:(id)parameters
fileData:(NSData *)fileData
succeed:(void (^)(id))succeed
failure:(void (^)(NSError *))failure
{
// 0.设置API地址
URLString = [NSString stringWithFormat:@"%@%@",BASE_URL,[URLString stringByReplacingOccurrencesOfString:@" " withString:@"%20"]]; DNSLog(@"\n POST上传文件参数列表:%@\n\n%@\n",parameters,[Utilit URLEncryOrDecryString:parameters IsHead:false]); // 1.创建请求管理者
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; // 2.申明返回的结果是二进制类型
manager.responseSerializer = [AFHTTPResponseSerializer serializer]; // 3.如果报接受类型不一致请替换一致text/html 或者 text/plain
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil]; // 4.请求超时,时间设置
manager.requestSerializer.timeoutInterval = 30; // 5. POST数据
[manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { //将得到的二进制数据拼接到表单中 /** data,指定上传的二进制流;name,服务器端所需参数名*/
[formData appendPartWithFileData :fileData name:@"file" fileName:@"audio.MP3" mimeType:@"audio/MP3"]; }progress:nil success:^(NSURLSessionDataTask *task, id responseObject) { NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; succeed([AFNManagerRequest dictionaryWithJsonString:responseStr]); } failure:^(NSURLSessionDataTask *task, NSError *error) { failure(error);
}];
} /*json
* @brief 把格式化的JSON格式的字符串转换成字典
* @param jsonString JSON格式的字符串
* @return 返回字典
*/
+(NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
if (jsonString == nil) {
return nil;
} NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&error];
if(error) {
DNSLog(@"json解析失败:%@",error);
return nil;
}
return dic;
} /*json
* @brief 把字典转换成字符串
* @param jsonString JSON格式的字符串
* @return 返回字符串
*/
+(NSString*)URLEncryOrDecryString:(NSDictionary *)paramDict IsHead:(BOOL)_type
{ NSArray *keyAry = [paramDict allKeys];
NSString *encryString = @"";
for (NSString *key in keyAry)
{
NSString *keyValue = [paramDict valueForKey:key];
encryString = [encryString stringByAppendingFormat:@"&"];
encryString = [encryString stringByAppendingFormat:@"%@",key];
encryString = [encryString stringByAppendingFormat:@"="];
encryString = [encryString stringByAppendingFormat:@"%@",keyValue];
} return encryString;
} @end<span style="color:#3333ff;">
</span>
最新 AFNetworking 3.0 简单实用封装的更多相关文章
- AFNetworking 3.0简单数据请求get&post
/** *get请求方法 */ - (void)AFNGetUrl { AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; ...
- [翻译] Working with NSURLSession: AFNetworking 2.0
Working with NSURLSession: AFNetworking 2.0 简单翻译,有很多错误,看官无法理解处请英文原文对照. http://code.tutsplus.com/tu ...
- .NET 跨平台RPC框架DotNettyRPC Web后台快速开发框架(.NET Core) EasyWcf------无需配置,无需引用,动态绑定,轻松使用 C# .NET 0配置使用Wcf(半成品) C# .NET Socket 简单实用框架 C# .NET 0命令行安装Windows服务程序
.NET 跨平台RPC框架DotNettyRPC DotNettyRPC 1.简介 DotNettyRPC是一个基于DotNetty的跨平台RPC框架,支持.NET45以及.NET Standar ...
- C# .NET Socket 简单实用框架,socket组件封装
参考资料 https://www.cnblogs.com/coldairarrow/p/7501645.html 根据.NET Socket 简单实用框架进行了改造,这个代码对socket通信封装还是 ...
- AFNetworking 3.0 源码解读 总结(干货)(下)
承接上一篇AFNetworking 3.0 源码解读 总结(干货)(上) 21.网络服务类型NSURLRequestNetworkServiceType 示例代码: typedef NS_ENUM(N ...
- AFNetworking 3.0 源码解读(八)之 AFImageDownloader
AFImageDownloader 这个类对写DownloadManager有很大的借鉴意义.在平时的开发中,当我们使用UIImageView加载一个网络上的图片时,其原理就是把图片下载下来,然后再赋 ...
- AFNetworking 3.0 源码解读(三)之 AFURLRequestSerialization
这篇就讲到了跟请求相关的类了 关于AFNetworking 3.0 源码解读 的文章篇幅都会很长,因为不仅仅要把代码进行详细的的解释,还会大概讲解和代码相关的知识点. 上半篇: URI编码的知识 关于 ...
- AFNetworking 3.0 源码解读(四)之 AFURLResponseSerialization
本篇是AFNetworking 3.0 源码解读的第四篇了. AFNetworking 3.0 源码解读(一)之 AFNetworkReachabilityManager AFNetworking 3 ...
- AFNetworking 2.0指北
AFNetworking 2.0 来了 SEP 30TH, 2013 前几天 Mattt 发布了 AFNetworking 2.0,我的一个最大感慨就是,他怎么那么高产? 关于 Mattt Mattt ...
随机推荐
- Mybatis全部标签
一.定义SQL语句 (1)select 标签的使用 属性介绍: id :唯一的标识符. parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User或user ...
- Problem W: 零起点学算法21——求平均值
#include<stdio.h> int main() { int a,b,c; scanf("%d %d %d",&a,&b,&c); pr ...
- display:block什么时候使用
所有的块级元素不需要再在使用display:block定义,块级元素本身的默认属性就是block display:block:比较常用于<a><span>这两个标签,因为他们不 ...
- Bean的装配方式
(一) 知识点:Spring容器支持多种形式的Bean的装配方式,比如基于XML的装配,基于注解的装配和自动装配(最常用的就是基于注解的装配) Spring提供了两种基于xml的装配方式:设值注入(S ...
- SQL server 2008 安装问题解决 转
http://www.cnblogs.com/Hackerman/p/4472811.html 安装sqlserver2008 出现的一些问题解决方法 1,安装sqlserver的时候出现如下图所 ...
- SQL:将查询结果插入到另一个表的三种情况!
一:如果要插入目标表不存在: select * into 目标表 from 表 where ... 二:如果要插入目标表已经存在: insert into 目的表 select * from 表 wh ...
- mysql 中查询一个字段是否为null的sql
查询mysql数据库表中字段为null的记录: select * 表名 where 字段名 is null 查询mysql数据库表中字段不为null的记录: select * 表名 where 字段名 ...
- 配置SSH单向无密码访问
服务器架构:系统:CentOS 6.5 x64主控端A:192.168.0.150远端主机B:192.168.0.151 原理: 利用ssh key生成公钥.私钥,密钥相当于一把钥匙,而公钥就相当于一 ...
- java获取src下包的文件的路径
String params = getClass().getClassLoader().getResource("system-config.properties").getPat ...
- OS中处理机调度模型和调度算法
OS中处理机调度模型和调度算法 调度层次 1.1. 高级调度(长程调度,作业调度) 功能:依据某种算法.把在外存队列上处于后备队列的那些作业调入内存.以作业为操做对象. 作业:比程序更为广泛的概念,不 ...