Created
June 27, 2024 09:32
-
-
Save yostane/6aac1fb721c00c565509dded883f7481 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Foundation | |
| import FoundationNetworking | |
| // URL session provides async and callback API to upload Data | |
| // Use continuations to convert existing callback API into an async | |
| // https://developer.apple.com/documentation/foundation/url_loading_system/uploading_data_to_a_website | |
| // You can POST to the /register endpoint of this API https://movie-api-ybwl.koyeb.app/api-docs/ | |
| enum HttpError: Error { | |
| case url, encode, emptyResponseBody(message: String) | |
| } | |
| typealias UploadResult = Result<Int, HttpError> | |
| struct User: Codable { | |
| let email: String | |
| let password: String | |
| let firstname: String | |
| let lastname: String | |
| } | |
| func uploadData(request: URLRequest, requestBody: Data, completion: @escaping (_ uploadResult: UploadResult) -> Void) { | |
| print("calling url", request) | |
| let uploadTask = URLSession.shared.uploadTask(with: request, from: requestBody) { data, _, error in | |
| print("inside callback") | |
| guard data != nil else { | |
| print("no response body") | |
| completion(.failure(.emptyResponseBody(message: error?.localizedDescription ?? ""))) | |
| return | |
| } | |
| print("got response body") | |
| completion(.success(0)) | |
| } | |
| uploadTask.resume() | |
| } | |
| func uploadDataAsync() async -> UploadResult { | |
| guard let url = URL(string: "https://movie-api-ybwl.koyeb.app/user/register") else { | |
| return .failure(.url) | |
| } | |
| var request = URLRequest(url: url) | |
| request.setValue("application/json", forHTTPHeaderField: "Content-Type") | |
| request.setValue("application/json", forHTTPHeaderField: "accept") | |
| request.httpMethod = "POST" | |
| let user = User(email: "email@email.com", password: "password", firstname: "John", lastname: "Doe") | |
| guard let encoded = try? JSONEncoder().encode(user) else { | |
| return .failure(.encode) | |
| } | |
| return await withCheckedContinuation { continuation in | |
| uploadData(request: request, requestBody: encoded) { continuation.resume(returning: $0) | |
| } | |
| } | |
| } | |
| let result = await uploadDataAsync() | |
| print("is successul ?", result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment