网络请求函数
当body为nil时为 Get请求,有值时为POST请求
func httpSend(url:String,body:Any?,completionHandler: @escaping(Data?, URLResponse?, Error?) -> Void){
//请求URL
let url:URL! = URL(string: url)
var request:URLRequest = URLRequest(url: url)
if body != nil{
//设置为POST请求
request.httpMethod = "POST"
var bodyData:Data!
//UTF8转码,防止汉字符号引起的非法网址
//设置请求体
switch body {
case is String:
bodyData = (body as! String).data(using: String.Encoding.utf8)
case is Data:
bodyData = (body as! Data)
default:
print("Unkown body type.")
}
request.httpBody = bodyData
}else{
request.httpMethod = "GET"
}
//默认session配置
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
//发起请求
let dataTask = session.dataTask(with: request, completionHandler: completionHandler)
//请求开始
dataTask.resume()
}
调用代码如下
//主线程
DispatchQueue.global().async {
let body = "data=[{\"name\":\"loginService\",\"package\":\"customer\",\"param\":{\"viewId\":\"popupLogin_view\",\"pageSize\":10,\"viewParam\":{},\"account\":\"xxxx\",\"password\":\"xxx\"}}]"
self.httpSend(url: "http://weima.joinlinking.com/breeze.brz", body: body, completionHandler: { (data, response, error) in
let obj = try?JSONSerialization.jsonObject(with: data!, options: .allowFragments)
print(obj)
//然后在此处
DispatchQueue.main.async {
//在主线程中执行
//该处可以修改ui等 如
self.title = "test"
}
})
}
代码的流程大概是首先在全局的一个异步线程队列中执行网络操作,然后在异步调用主线程执行ui操作