swift5网络请求. post代码异步执行,并进行封装
时间: 2024-01-16 10:02:47 浏览: 144
以下是使用Swift进行异步执行的POST请求代码:
```swift
func postData(url: String, parameters: [String: Any], completion: @escaping (Data?, Error?) -> Void) {
guard let url = URL(string: url) else {
completion(nil, NSError(domain: "Invalid URL", code: 0, userInfo: nil))
return
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
do {
let jsonData = try JSONSerialization.data(withJSONObject: parameters, options: [])
request.httpBody = jsonData
} catch {
completion(nil, error)
return
}
let session = URLSession.shared
let task = session.dataTask(with: request) { data, response, error in
if let error = error {
completion(nil, error)
return
}
guard let data = data else {
completion(nil, NSError(domain: "No Data", code: 0, userInfo: nil))
return
}
completion(data, nil)
}
task.resume()
}
```
这个函数将URL和参数作为输入,并在完成时传递数据和错误。它首先将参数转换为JSON格式,然后设置POST请求的HTTP正文。然后使用共享URL会话创建一个数据任务,并在异步完成后调用完成块。
阅读全文