在使用Alamofire时,可以将异步代码包装在一个async块中,并使用await
关键字等待网络请求返回响应。此外,responseString()
方法可以替换serializingString().response
方法来获取响应。以下是修改后的示例代码:
import Alamofire
func fetchPosts() async throws -> [Post] {
let url = "https://jsonplaceholder.typicode.com/posts"
let request = AF.request(url)
let response = try await request.responseString()
let posts = try JSONDecoder().decode([Post].self, from: response.data(using: .utf8)!)
return posts
}
这段代码会从指定的URL异步请求JSON数据,然后使用Alamofire的responseString()
方法获取响应。最后,使用JSONDecoder解码响应,并返回包含Post对象的数组。