Swift_2022_网络请求
一、网络请求步骤
- 设置请求
url
设置
URLRequest
对象,配置请求相关信息- 创建会话配置
URLSessionConfiguration
创建会话
URLSession
创建任务和设置请求回调,并发起请求
一般通过以上几个步来完成网络请求,当然要根据不同应用场景来配置请求属性。
二、使用
1、原生
json转dic
//json转dic func getDictionaryFromJSONString(jsonString:String) ->NSDictionary{ let jsonData:Data = jsonString.data(using: .utf8)! let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) if dict != nil { return dict as! NSDictionary } return NSDictionary() }
Get
func makeLogon() { // 构建URL let url:URL = URL(string: "https://xxx/xxx/API?xxx")! // 发送HTTP请求的的session对象 let session = URLSession.shared // 构建请求request var request = URLRequest(url: url) request.httpMethod = "GET" // 发一个get请求 let task = session.dataTask(with: request as URLRequest) {( data, response, error) in guard let data = data, let _:URLResponse = response, error == nil else { print("error") return } let dataString = String(data: data, encoding: String.Encoding.utf8) let dict = self.getDictionaryFromJSONString(jsonString: dataString!) print(dict) } task.resume() }
Post
func makeUpdateCountSheet() { // 这里直接使用 jsonString 转成字典,然后转成 Data,将 流 放到 request的 httpBody中, 模拟发送一个http请求 let jsonString = "{\"Data\":{\"xxx\":\"834\",\"xxx\":[{\"xxx\":[{\"xxx\":\"031019\",\"xxx\":\"ADD\",\"xxx\":\"9\"},{\"xxx\":\"5651G-06920ADBAA\",\"xxx\":\"ADD\",\"xxx\":\"6\"}],\"xxx\":\"xxx\",\"Counted\":true,\"xxx\":true,\"LineNum\":\"1\",\"xxx\":\"235\",\"Quantity\":\"15\"}],\"xxx\":\"\",\"Initials\":\"we\",\"xxx\":true},\"xxx\":\"\"}" let dict = self.getDictionaryFromJSONString(jsonString: jsonString) print(dict) var jsonData = NSData() do { jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) as NSData } catch { print(error.localizedDescription) } // 构建URL let url:URL = URL(string: "https://xxx/xxx/API?xxx")! // session let session = URLSession.shared // request var request = URLRequest(url: url) request.httpMethod = "POST" // 设置Content-Length,非必须 request.setValue("\(jsonData.length)", forHTTPHeaderField: "Content-Length") // 设置 Content-Type 为 json 类型 request.setValue("application/json", forHTTPHeaderField: "Content-Type") // POST 请求将 数据 放置到 请求体中 request.httpBody = jsonData as Data // 发送请求 let task = session.dataTask(with: request as URLRequest) {( data, response, error) in guard let data = data, let _:URLResponse = response, error == nil else { print("error") return } // 返回值 utf8 转码 let dataString = String(data: data, encoding: String.Encoding.utf8) // 将 jsonString 转成字典 let dict = self.getDictionaryFromJSONString(jsonString: dataString!) print(dict) } task.resume() }
2、Alamofire
3、Moya+Alamofire
Moya是一个对Alamofire封装的库,提供简洁的接口供开发者调用,抽象了URL和Parameters来帮助使用者生成urlRequest,最后通过alamofire发起请求。
具体使用时在Moya和Your App之间加一层Rx,用于处理请求回来的数据