swift-发送JSON数据给服务器

之前用OC写代码时候,直接用AFN可以实现传json,swift项目中也有json传值,但都是有key的,key={}格式,现在后台必须要让直接传json,说不愿意修改自己的东西,好吧,前端实现吧,于是在原文中找到引用AFN的方式,感谢原作者,再次记录一下:

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


image.png

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


image.png

如果请求要设置请求头,切记一定要讲请求头设置放在manager.requestSerializer = AFJSONRequestSerializer()之后,我就因为放在之前调试了很久...

调用方法:至此调用json格式请求给服务器就成功了!!!


image.png
import UIKit
import AFNetworking


//MARK: - post请求 无key和value的json传参方式
/*
 methodIsPOST:是否是post请求
 URLString:url链接
 parameters:需要传的包
 headerValue:请求头的value
 */

class HJNetworkManager: AFHTTPSessionManager {
    static let shared = HJNetworkManager()

    func json_request(methodIsPOST:Bool, URLString:String, parameters:[String : AnyObject]?,headerValue:String, completion:@escaping (_ json :AnyObject?, _ :Bool) -> ()){

        // 成功回调
        let success = { (task:URLSessionDataTask ,json:Any?)->Void in
            completion(json as AnyObject?, true)
        }
   
        // 失败回调
        let failure = { (task:URLSessionDataTask?, error:Error)->() in
            print("网络请求错误:\(error)")
            completion(nil, false)
        }

        let manager = AFHTTPSessionManager()
        // json请求
        manager.requestSerializer = AFJSONRequestSerializer()
        // 设置请求头
//        manager.requestSerializer.setValue(headerValue, forHTTPHeaderField: "token")
        manager.requestSerializer.setValue(headerValue, forHTTPHeaderField: "Authorization")

//        var headerDict = [String : String]()
//        let access_token = BaseUser.shareUser().getAccess_token()
//        headerDict = ["Authorization":"bearer " + access_token]
        
        if methodIsPOST == true {
            manager.post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else{
            manager.get(URLString, parameters: parameters, progress: nil, success: success, failure: failure )
        }
    }

   
}


调用的代码如下:

func creatLiBaoDataSource(){
    let url = BaseURLAPi.AutoziJLApiMAgentGiftPackAddWith()
    let formDict = self.changeParamJSON()
    //请求头
    let access_token = BaseUser.shareUser().getAccess_token()
    let headerValue = "bearer " + access_token
    HJNetworkManager.shared.json_request(methodIsPOST: true, URLString: url, parameters: formDict as? [String:AnyObject], headerValue: headerValue) { (dict:AnyObject?, isSuccess:Bool) in
        if isSuccess{
            LSPrint(message: "返回的全部数据为:\(dict ?? "" as AnyObject)")
        }else{
            
        }
    }
 
   }
    
    //组件字典
    func changeParamJSON() -> NSDictionary{
        let paramDic = NSMutableDictionary()
        paramDic.setValue("1277530606967808001", forKey: "goodsId")
        paramDic.setValue("1277533881163145217", forKey: "goodsCatalogId")
        paramDic.setValue("3", forKey: "goodsNum")
        paramDic.setValue("测试", forKey: "giftPackName")
        return paramDic
    }

本章出自:https://www.jianshu.com/p/b42418fa0f92
感谢原作者!
转载请注明出处,谢谢配合!

你可能感兴趣的:(swift-发送JSON数据给服务器)