SwiftCairo
Published in

SwiftCairo

Better? Enums are your best friend on this

Protocol-Oriented Network in swift

Network layer as a static function in a 1000 line class!
UserRequest.login(name:nameTF.text!, pass: passTF.text!).sendRequest{ response in ... }
Meet crusty, from Apple WWDC presentation

URLRequest:

So how to create it? Meet the “Router” way:

func asURLRequest() throws -> URLRequest { }
enum TodoRouter: URLRequestConvertible {
static let baseURLString = "https://jsonplaceholder.typicode.com/"

case get(Int)
case create([String: Any])
case delete(Int)

func asURLRequest() throws -> URLRequest {
var method: HTTPMethod {
switch self {
case .get:
return .get
case .create:
return .post
case .delete:
return .delete
}
}

let params: ([String: Any]?) = {
switch self {
case .get, .delete:
return nil
case .create(let newTodo):
return (newTodo)
}
}()

let url: URL = {
// build up and return the URL for each endpoint
let relativePath: String?
switch self {
case .get(let number):
relativePath = "todos/\(number)"
case .create:
relativePath = "todos"
case .delete(let number):
relativePath = "todos/\(number)"
}

var url = URL(string: TodoRouter.baseURLString)!
if let relativePath = relativePath {
url = url.appendingPathComponent(relativePath)
}
return url
}()

var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = method.rawValue

let encoding: ParameterEncoding = {
switch method {
case .get:
return URLEncoding.default
default:
return JSONEncoding.default
}
}()
return try encoding.encode(urlRequest, with: params)
}
}
Postman API collection

URLRequestBuilder:

None Alamofire users:

func asURLRequest() throws -> URLRequest

let’s see UserRequests enum:

ServerPath is an enum with strings for the server paths, it looks like this:

Serverpaths enum
let request = UserRequest.login(email: “sent email”, password: “password”)Alamofire.request(request).response ...

More where this came from

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abdoelrhman Mohamed

Mobile software engineer @Adevinta, working with swift and iOS mainly, and community founder @SwiftCairo @LintSchool