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 简单实用封装的更多相关文章

  1. AFNetworking 3.0简单数据请求get&post

    /** *get请求方法 */ - (void)AFNGetUrl { AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; ...

  2. [翻译] Working with NSURLSession: AFNetworking 2.0

    Working with NSURLSession: AFNetworking 2.0   简单翻译,有很多错误,看官无法理解处请英文原文对照. http://code.tutsplus.com/tu ...

  3. .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 ...

  4. C# .NET Socket 简单实用框架,socket组件封装

    参考资料 https://www.cnblogs.com/coldairarrow/p/7501645.html 根据.NET Socket 简单实用框架进行了改造,这个代码对socket通信封装还是 ...

  5. AFNetworking 3.0 源码解读 总结(干货)(下)

    承接上一篇AFNetworking 3.0 源码解读 总结(干货)(上) 21.网络服务类型NSURLRequestNetworkServiceType 示例代码: typedef NS_ENUM(N ...

  6. AFNetworking 3.0 源码解读(八)之 AFImageDownloader

    AFImageDownloader 这个类对写DownloadManager有很大的借鉴意义.在平时的开发中,当我们使用UIImageView加载一个网络上的图片时,其原理就是把图片下载下来,然后再赋 ...

  7. AFNetworking 3.0 源码解读(三)之 AFURLRequestSerialization

    这篇就讲到了跟请求相关的类了 关于AFNetworking 3.0 源码解读 的文章篇幅都会很长,因为不仅仅要把代码进行详细的的解释,还会大概讲解和代码相关的知识点. 上半篇: URI编码的知识 关于 ...

  8. AFNetworking 3.0 源码解读(四)之 AFURLResponseSerialization

    本篇是AFNetworking 3.0 源码解读的第四篇了. AFNetworking 3.0 源码解读(一)之 AFNetworkReachabilityManager AFNetworking 3 ...

  9. AFNetworking 2.0指北

    AFNetworking 2.0 来了 SEP 30TH, 2013 前几天 Mattt 发布了 AFNetworking 2.0,我的一个最大感慨就是,他怎么那么高产? 关于 Mattt Mattt ...

随机推荐

  1. 【费马小定理+快速幂+逆元】BZOJ3240-[NOI2013]矩阵游戏

    [题目大意] 若用F[i][j]来表示矩阵中第i行第j列的元素,则F[i][j]满足下面的递推式:F[1][1]=1F[i,j]=a*F[i][j-1]+b (j!=1)①F[i,1]=c*F[i-1 ...

  2. 用python 将 pymysql操作封装成类

    觉得代码啰嗦的可以把logging日志删掉,但是工程中时刻要记得写日志 import pymysql import logging import sys # 加入日志 #获取logger实例 logg ...

  3. iOS开发 Swift开发数独游戏(五)显示游戏答案

          要点是设置好Tag就好,通过代码找到并初始化即可. 1: // 2: // ShowAnswerController.swift 3: // sudoku-v02 4: // 5: // ...

  4. maven-pom-build

    地址: http://blog.csdn.net/taiyangdao/article/details/52374125

  5. 常见的 HTTP 状态代码及原因

    代码 说明 备注 200 确定 IIS 7.0.IIS 7.5 和 IIS 8.0 成功处理了请求. 304 未修改 客户端浏览器请求已处于缓存中的文档,并且自从该文档被缓存后,未修改此文档.客户端浏 ...

  6. centos 7.3systemctl工具

    http://www.cnblogs.com/tswcypy/p/4479153.html

  7. 《新一代视频压缩码标准-H.264_AVC》读书笔记1

    摘要 第一章 绪论 正文 1.一般而言,视频信号信息量大,传输网络所需要的带宽相对较宽.例如,一路可视电话或会议电视信号,由于其活动内容较少,所需带宽较窄,但要达到良好质量,不压缩约需若干 Mbps, ...

  8. 剪切Postscript图片中的多余边框

    最近用plplot画图,其cairo ps库生成的ps图片总是不能合理地剪切掉多余的边框,于是乎自己写了一个小脚本epscrop,用修改ps图的BoundingBox. #!/bin/bash # c ...

  9. JavaScript破解验证码

    现在,Megaupload站点提供的CAPTCHA在上述代码面前已经败下阵来,说实话,这里的验证码设计的不不太好.但更有趣的是: 1.HTML 5中的Canvas应用程序接口getImageData可 ...

  10. http://blog.sina.com.cn/s/blog_628cc2b70102v115.html

    http://blog.sina.com.cn/s/blog_628cc2b70102v115.html