0封装一层工具类,swift发送JSON数据给服务器

新近做的种类里面有一条扩展沟通人的须求,,何况须求是传json格式的字符串给后台,而且字符串是多少个字典类型的,首先项目用OC写的,弄了段日子毕竟幸不辱命了,然后后天选拔swift重新写项目玩,swift发送JSON数据给服务器在网上找了半天都并未有找到答案,经过努力终于完毕了弄了多少个小时终于弄通了.在此分享一下,并且有个alamofire的难点向各位大神请教.

#import

Demo 下载地址 :

//枚举 须求格局

enum HTTPMethod : Int{

case  GET = 0

case  POST = 1

}

class NetWorkTools: AFHTTPSessionManager {

//设置NetWorkTools单例对象 推行闭包

static let shareInstance :NetWorkTools = {

let tools = NetWorkTools()

tools.responseSerializer.acceptableContentTypes?.insert("text/html")

return tools

}()

}

//分类  GET POST互连网央浼

extension NetWorkTools {

func request(requestType : HTTPMethod, url : String, parameters : [String : Any]?, succeed : @escaping([String : Any]?) -> (), failure : @escaping(Error?) -> ()) {

// 定义成功闭包

let successBlock = { (task: URLSessionDataTask, responseObj: Any?) in

succeed(responseObj as? [String : Any])

}

// 定义败北的闭包

let failureBlock = { (task: URLSessionDataTask?, error: Error) in

failure(error)

}

// Get 请求

if requestType == .GET {

get(url, parameters: parameters, progress: nil, success: successBlock, failure: failureBlock)

}

// Post 请求

if requestType == .POST {

post(url, parameters: parameters, progress: nil, success: successBlock, failure: failureBlock)

}

}

上传图片

// MARK: - 封装 AFN 方法

/// 上传文件必须是 POST 方法,GET 只可以获取数据

/// 封装 AFN 的上传文件格局

///

/// - parameter URLString:  URLString

/// - parameter parameters: 参数字典

///uploadProgress 进程指标

/// - parameter img:      UIImage对象

/// - parameter completion: 完毕回调

func unload(urlString: String, parameters: AnyObject?, img : UIImage , uploadProgress: ((_ progress:Progress) -> Void)?, success: ((_ responseObject:AnyObject?) -> Void)?, failure: ((_ error: NSError) -> Void)?) -> Void {

post(urlString, parameters: parameters, constructingBodyWith: { (formData) in

let imageData = UIImageJPEGRepresentation(img, 0.8)

formData.appendPart(withFileData: imageData!, name: "upload", fileName: "head.img", mimeType: "image/jpeg")

}, progress: { (progress) in

uploadProgress!(progress)

}, success: { (task, objc) in

if objc != nil {

success!(objc as AnyObject?)

}

}, failure: { (task, error) in

failure!(error as NSError)

})

}

席卷简易的SnapKit的应用

git地址 :

@interfaceDFS_NetworkTool :NSObject

标题:在选用alamofire发送央求时候,调用发送json格式总是报错,求答案!!!

#import "AFNetworking.h"

 (_Nonnullinstancetype)sharedNetworkTool;

网络找答案是:encoding:ParameterEncoding.JSON,不过自身怎么用怎么改都以错...,最终选择了AFN框架才落到实处了效用.

@interface HttpRequest : NSObject

/**

图片 1

typedef void(^success)(NSURLSessionDataTask *task, id responseObject);

*发送POST请求

先是讲下OC中发送JSON格式数据给服务器:如下图↓

typedef void(^failure)(NSURLSessionDataTask *task, NSError *error);

*

图片 2

(void)POST:(NSString *)URLString

*@param U途观LString供给的地址

在此说美素佳儿(Friso)个标题:关于AFN内部存款和储蓄器泄漏难点

parameters:(NSMutableDictionary *)parameters andSuccess:(success)successBlock andFailure:(failure)failureBlock;

*@param parameters 诉求参数

// AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];

@end

*@param finished乞求完结回调

应用方面方式呼吁数据会招致内部存款和储蓄器泄漏,因为她不是多少个单例!所以开拓中我们要将AFHTTPSessionManager写成单例再去调用,明天instrument测验无意间发掘的,英特网海人民广播电视台湾大学以此答案


*/

AFHTTPSessionManager *mgr = [self getManager];

#import "HttpRequest.h"

- (void) POST:(nonnullNSString*) URLString parameters:(nullableNSDictionary*) parameters finished:(nonnullvoid(^)(id_NullableresponseObject,NSError*_Nullableerror ))finished;

mgr.requestSerializer = [AFJSONRequestSerializer serializer];(发送json格式给后台)

#define kTimeOutInterval 20.0f

/**

上边要说的是: swift发送json格式字符串给后台,使用AFN,如下图 ↓

@implementation HttpRequest

*发送GET请求

图片 3

(AFHTTPSessionManager *)manager

*

要是央求要设置央浼头,切记一定要讲央求头设存放在manager.requestSerializer = AFJSONRequestSerializer()之后,小编就因为身处在此之前调节和测量检验了相当久...

{

*@param ULX570LString诉求的地点

调用方法:至此调用json格式央浼给服务器就水到渠成了!!!

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

*@param parameters 诉求参数

图片 4

// 超时时间

*@param finished诉求达成回调

贴代码:方便使用:

manager.requestSerializer.timeoutInterval = kTimeOutInterval;

*/

class HJNetworkManager: AFHTTPSessionManager {

// 申明上传的是json格式的参数,需求你和后台约定好,不然会冒出后台不能够赢得到你上传的参数难点

- (void) GET:(nonnullNSString*) URLString parameters:(nullableNSDictionary*) parameters finished:(nonnullvoid(^)(id_NullableresponseObject,NSError*_Nullableerror ))finished;

static let shared = HJNetworkManager()

manager.requestSerializer = [AFHTTPRequestSerializer serializer]; // 上传普通格式

.m文件

func json_request(method:HJHTTPMethod = .POST, URLString:String, parameters:[String : AnyObject]?,headerValue:String, completion:@escaping (_ json :AnyObject?, _ :Bool) -> {

//    manager.requestSerializer = [AFJSONRequestSerializer serializer]; // 上传JSON格式

@interfaceDFS_NetworkTool()

// 成功回调

// 申明获得到的数码格式

/**

let success = { (task:URLSessionDataTask ,json:Any?)->Void in

manager.responseSerializer = [AFHTTPResponseSerializer serializer]; // AFN不会剖析,数据是data,要求团结深入分析

*AFHTTPSessionManager 属性

completion(json as AnyObject?, true)

//    manager.responseSerializer = [AFJSONResponseSerializer serializer]; // AFN会JSON深入分析重回的数目

*/

}

// 个人提出依然友好深入分析的相比好,不常接口再次来到的数据不沾边会报3840张冠李戴,大致是AFN无法剖析再次来到来的数量

@property(nonatomic,strong)AFHTTPSessionManager*manager;

// 战败回调

return manager;

@end

let failure = { (task:URLSessionDataTask?, error:Error)->() in

}

@implementationDFS_NetworkTool

print("互连网要求错误:

(void)POST:(NSString *)URLString

(instancetype)sharedNetworkTool

completion(nil, false)

parameters:(NSMutableDictionary *)parameters andSuccess:(success)successBlock andFailure:(failure)failureBlock

{

}

{

staticDFS_NetworkTool*instance;

let manager = AFHTTPSessionManager()

// 创建央求类

staticdispatch_once_tonceToken;

// json请求

AFHTTPSessionManager *manager = [self manager];

dispatch_once(&onceToken, ^{

manager.requestSerializer = AFJSONRequestSerializer()

[manager POST:URLString

instance = [[DFS_NetworkToolalloc]init];

// 设置恳求头

parameters:parameters

//需要json请求

manager.requestSerializer.setValue(headerValue, forHTTPHeaderField: "token")

progress:^(NSProgress * _Nonnull uploadProgress) {

//instance.manager.requestSerializer = [AFJSONRequestSerializer serializer];

if method == .POST {

// 这里可以得到到当前数据哀求的进度

//instance.manager.responseSerializer = [AFJSONResponseSerializer serializer];

manager.post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)

} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

// 提醒 : 有不供给当心的地方? text/html

}else{

// 央浼成功

instance.manager.responseSerializer.acceptableContentTypes= [NSSetsetWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",@"text/plain",nil];

manager.get(URLString, parameters: parameters, progress: nil, success: success, failure: failure )

if (successBlock) {

});

}

successBlock(task,responseObject);

returninstance;

}

}

}

}

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

- (instancetype) init {

仅供我们仿效,不得法之处望大神讨论指正,大家一起前行!~☺️

// 乞求退步

if(self= [superinit]) {

if (failureBlock) {

//调用manager每一遍创设三个新的AFHTTPSessionManager对象

failureBlock(task,error);

//默认是 AFHTTPRequestSerializer

}

self.manager= [AFHTTPSessionManagermanager];;

}];

}

}

returnself;

@end

}

- (void) POST:(NSString*) URLString parameters:(nullableNSDictionary*) parameters finished:(void(^)(idresponseObject,NSError*error ))finished {

//调用AFN的POST方法

[self.managerPOST:URLStringparameters:parametersprogress:nilsuccess:^(NSURLSessionDataTask*_Nonnulltask,id_NullableresponseObject) {

//回调

finished(responseObject,nil);

}failure:^(NSURLSessionDataTask*_Nullabletask,NSError*_Nonnullerror) {

finished(nil,error);

}];

}

- (void) GET:(NSString*) URLString parameters:(nullableNSDictionary*) parameters finished:(void(^)(idresponseObject,NSError*error ))finished {

//调用AFN的POST方法

[self.managerGET:URLStringparameters:parametersprogress:nilsuccess:^(NSURLSessionDataTask*_Nonnulltask,id_NullableresponseObject) {

//回调

finished(responseObject,nil);

}failure:^(NSURLSessionDataTask*_Nullabletask,NSError*_Nonnullerror) {

finished(nil,error);

}];

}

@end

本文由星彩网app下载发布于计算机编程,转载请注明出处:0封装一层工具类,swift发送JSON数据给服务器

TAG标签: 星彩网app下载
Ctrl+D 将本页面保存为书签,全面了解最新资讯,方便快捷。