Native networking solution that uses concepts from Axios.js
import Avios
struct Post: Codable {
var userId: Int
var id: Int
var title: String
var body: String
}
func fetchPosts() async throws {
// Getting data
// Available methods are: .get, .post, .patch, .update, .put, .delete
let (data, response) = try await Avios.shared.get("https://jsonplaceholder.typicode.com/posts")
// Handling response
guard response.isOk() else { throw Error }
// Handling status code
switch response.httpResponse?.statusCode {
case 200:
print("Status code is 200 (OK)")
case 201:
print("Status code is 201 (CREATED)")
// etc...
}
// Decoding data
let posts: [Post] = try JSON.parse(data)
return posts
}struct PostDto: Codable {
var title: String
var body: String
var usedId: Int
}
let body = PostDto(title: "foo", body: "bar", usedId: 1)
// The logic is the same as written before, but you have to pass
// body argument that conforms to Encodable
let (data, res) = try await Avios.shared.post(typicodeUrl("posts"), body: body, headers: [
"Content-type": "application/json; charset=UTF-8"
])- Base URL option
