网络请求框架用多了,之后发现自己的网络知识都忘了,现在的项目中有一个需求需要给json数据post给服务器,针对这个问题,我又一次入坑了,因为以前一直都是讲参数放在字典里发送给服务器的,但是在这一次,需要给json数据发送给服务器
首先看一下,我需要提交给服务器的json字符串长什么样子的,
[
{
“express_id” : “101”,
“scan_time” : “2017-03-18 10:42:00”,
“mail_no” : “55636”,
“cus_name” : “不仅仅就”,
“mail_weight” : “5556”,
“operator” : “罗文”,
“operator_id” : 10000369,
“op_type” : 0,
“emp_id” : 10000369
},
{
“express_id” : “101”,
“scan_time” : “2017-03-18 10:42:08”,
“mail_no” : “55366”,
“cus_name” : “韩语uu”,
“mail_weight” : “5556”,
“operator” : “罗文”,
“operator_id” : 10000369,
“op_type” : 0,
“emp_id” : 10000369
}
]
像这种字符串只能转成一个数组,我们的请求框架直接传字典,我不得不想起了。我想起的原生的URLsession,来解决这个问题,确实也解决了这些问题,直接上代码了
/* 创建Post请求 */
func PostRequest(data:String,str1:String)
{
//(1)设置请求路径
let url:NSURL = NSURL(string:"http://120.76.239.217:8000/EApi/sprecords/10000369/")!//不需要传递参数
//(2) 创建请求对象
let request:NSMutableURLRequest = NSMutableURLRequest(url: url as URL) //默认为get请求
request.timeoutInterval = 5.0 //设置请求超时为5秒
request.httpMethod = "POST" //设置请求方法
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
//设置请求体
//把拼接后的字符串转换为data,设置请求体
print(data)
request.httpBody = data.data(using: .utf8)
let session = URLSession.shared
//(3) 发送请求
let task = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
print(data ?? 9)
print(response ?? 0)
print(error ?? 9)
var dict:NSDictionary? = nil
do {
dict = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.init(rawValue: 0)) as? NSDictionary
} catch {
}
print("%@",dict ?? 0)
})
task.resume()
}
上述的代码,是基于swift3.0,原理也简单,将json字符串放在请求体的内部,当然还需要对请求的对象做一些配置,最后要说的是服务器返回的数据其实是在data当中,我们将它解析之后,就可以做我们想要做的操作
//继续上面的代码,当我用NSURLSession实现了这一功能,之后我们可能会觉得,项目中,有多处需要发送json,我们需要每次都去写配置请求的代码吗,当然不会了,这时我对网络请求封装一下
import UIKit
import Alamofire
enum MethodType{
case GET
case POST
}
class NetworkTools: NSObject {
class func GetDataByNSURLSession(_ dataS:Data,URLstr:String,finishCallBack:@escaping (_ result: AnyObject)->()){
//(1)设置网络请求路径
let url:NSURL = NSURL(string:URLstr)!//不需要传递参数
//(2) 创建请求对象
let request:NSMutableURLRequest = NSMutableURLRequest(url: url as URL) //默认为get请求
request.timeoutInterval = 5.0 //设置请求超时为5秒
request.httpMethod = "POST" //设置请求方法
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
//设置请求体
//把拼接后的字符串转换为data,设置请求体
request.httpBody = dataS
let session = URLSession.shared
//(3) 发送请求
let task = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
print(data ?? 9)
print(response ?? 0)
print(error ?? 9)
var dict:[String:AnyObject]? = nil
do {
dict = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.init(rawValue: 0)) as? NSDictionary as! [String : AnyObject]?
} catch {
}
print("%@",dict ?? 0)
finishCallBack(dict as AnyObject)
})
task.resume()
}}
``下面就是调用NetworkTools封装网络请求,我们可以将所有的请求放在一个方法中`
//3.45保存收派件记录```
class func saveAccept(dataStr:String,_ finishCallBack: @escaping(_ result: AnyObject)->()){
let url :String = String.init(format: "http://120.76.239.217:8000/EApi/sprecords/%d/", (UserAccount.account?.id)!)
let data = dataStr.data(using: .utf8)
NetworkTools.GetDataByNSURLSession(data!, URLstr: url) { (response) in
finishCallBack(response)
}
}