Skip to content

Instantly share code, notes, and snippets.

@mikekavouras
Created June 20, 2023 16:17
Show Gist options
  • Save mikekavouras/0bb847c1be5f9456aa9fff1b39af45a6 to your computer and use it in GitHub Desktop.
Save mikekavouras/0bb847c1be5f9456aa9fff1b39af45a6 to your computer and use it in GitHub Desktop.
Swift Router (w/ Alamofire)
//
// RouterNext.swift
// FootstepsAI
//
// Created by Mike Kavouras on 5/23/23.
//
import Foundation
import Alamofire
import KeychainSwift
import UIKit
enum Router: URLRequestConvertible {
case ping
case login(username: String, password: String)
private var method: HTTPMethod {
switch self {
case .ping, .login
}
}
private var path: String {
switch self {
case .ping:
return "/ping"
case .login:
return "/login"
}
}
private var params: Parameters? {
switch self {
case .ping:
return nil
case .login(let username, let password):
return ["username": username, "password": password]
}
}
private var headers: HTTPHeaders? {
switch self {
case .ping, .login:
return nil
}
}
func asURLRequest() throws -> URLRequest {
var url = URL("https://site.com")!
url = url.appendingPathComponent("/api")
var request = URLRequest(url: url.appendingPathComponent(path))
request.httpMethod = method.rawValue
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "content-Type")
do {
request.httpBody = try JSONSerialization.data(withJSONObject: baseParams.merge(params))
}
if let headers = headers {
request.headers = headers
}
return request
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment