Skip to content

Instantly share code, notes, and snippets.

View ekscrypto's full-sized avatar

Dave Poirier ekscrypto

View GitHub Profile
@ekscrypto
ekscrypto / MyEnum.swift
Last active May 18, 2022 12:43
RawRepresentable ~ prefix
enum AppStorageKeys: String {
case activeEnvironment
}
@ekscrypto
ekscrypto / TypeSafeUserDefaults v2.swift
Created March 25, 2022 13:17
Basic TypeSafeUserDefaults
class TypeSafeUserDefaults {
enum IntegerKey: StringLiteralType, RawRepresentable {
case myIntegerValue
}
enum StringKey: StringLiteralType, RawRepresentable {
case myStringValue
}
//
// OreCalculator.swift
// AdventOfCode2019-Day14
//
// Created by Dave Poirier on 2019-12-14.
// Copyright © 2019 Soft.io. All rights reserved.
//
import Foundation
extension APIRequest {
public static func urlRequest(from request: APIEndpoint) -> URLRequest? {
let endpoint = request.endpoint()
guard let endpointUrl = URL(string: "\(AppSettings.shared.serverBaseAddress)\(endpoint)") else {
return nil
}
var endpointRequest = URLRequest(url: endpointUrl)
endpointRequest.addValue("application/json", forHTTPHeaderField: "Accept")
return endpointRequest
extension APIRequest {
public static func processResponse<T: Codable, E: Codable>(
_ dataOrNil: Data?,
_ urlResponseOrNil: URLResponse?,
_ errorOrNil: Error?,
onSuccess: ((_: T) -> Void),
onError: ((_: E?, _: Error) -> Void)) {
if let data = dataOrNil {
do {
extension APIRequest {
public static func post<R: Codable & APIEndpoint, T: Codable, E: Codable>(
request: R,
onSuccess: @escaping ((_: T) -> Void),
onError: @escaping ((_: E?, _: Error) -> Void)) {
guard var endpointRequest = self.urlRequest(from: request) else {
onError(nil, APIError.invalidEndpoint)
return
}
import Foundation
protocol APIEndpoint {
func endpoint() -> String
}
class APIRequest {
struct ErrorResponse: Codable {
let status: String
let code: Int
APILoginRequest(email: email, password: password)
.dispatch(
onSuccess: { (successResponse) in
...
},
onFailure: { (errorResponse, error) in
...
})
extension APILoginRequest: APIEndpoint {
func endpoint() -> String {
return "/api/login"
}
func dispatch(
onSuccess successHandler: @escaping ((_: APILoginSuccessResponse) -> Void),
onFailure failureHandler: @escaping ((_: APIRequest.ErrorResponse?, _: Error) -> Void)) {
APIRequest.post(
struct APILoginSuccessResponse: Codable {
let status: String
let accesstoken: String
let refreshtoken: String
let expiresin: Int
}