Created
October 3, 2022 19:02
-
-
Save dmikots/4a28849b46845f66997ef040249e579d to your computer and use it in GitHub Desktop.
netw.swift
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 SwiftUI | |
enum Endpoint: RawRepresentable { | |
init?(rawValue: String) { nil } | |
case editUserImage | |
var rawValue: String { | |
switch self { | |
case .editUserImage: | |
return "/graph-files/avatar/save" | |
} | |
} | |
} | |
enum RequestMethod: String { | |
case get = "GET" | |
case post = "POST" | |
} | |
enum NetworkError: Error { | |
case errorRequest(error: Error) | |
case errorResponse | |
case errorData | |
case errorDecode(error: Error) | |
} | |
struct Response<Model: Decodable>: Decodable { | |
let success: Bool | |
let data: Model? | |
} | |
struct EmptyModel: Decodable {} | |
class NetworkLayer { | |
static let shared = NetworkLayer() | |
@AppStorage("accessToken") var token: String = "" | |
func postMethod(expecting: ImageOutput, completion: @escaping (Result<ImageInput, NetworkError>) -> Void) { | |
guard let url = URL(string: "https://staging.raceroom.live/api/graph-files/graph-avatar/save") else { | |
print("Error: cannot create URL") | |
return | |
} | |
// Convert model to JSON data | |
guard let jsonData = try? JSONEncoder().encode(expecting) else { | |
print("Error: Trying to convert model to JSON data") | |
return | |
} | |
// Create the url request | |
var request = URLRequest(url: url) | |
request.httpMethod = "POST" | |
request.setValue("application/json", forHTTPHeaderField: "Content-Type") | |
request | |
.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") | |
request.httpBody = jsonData | |
URLSession.shared.dataTask(with: request) { data, response, error in | |
guard error == nil else { | |
print("Error: error calling POST") | |
print(error!) | |
return | |
} | |
guard let data = data else { | |
completion(.failure(.errorData)) | |
return | |
} | |
guard let response = response as? HTTPURLResponse, (200 ..< 299) ~= response.statusCode else { | |
print("Error: HTTP request failed") | |
return | |
} | |
do { | |
let decoder = JSONDecoder() | |
let decodedResponse = try decoder.decode(ImageInput.self, from: data) | |
completion(.success(decodedResponse)) | |
print(decodedResponse) | |
} catch { | |
completion(.failure(.errorDecode(error: error))) | |
} | |
}.resume() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment