Skip to content

Instantly share code, notes, and snippets.

@thinkclay
Last active May 12, 2020 17:26
Show Gist options
  • Save thinkclay/5e2257a080891efd5cb5934e3c3ff92d to your computer and use it in GitHub Desktop.
Save thinkclay/5e2257a080891efd5cb5934e3c3ff92d to your computer and use it in GitHub Desktop.
Swift iOS Networking Service
import Foundation
struct VOService {
public var baseUrl: String
static let shared = VOService(mode: .production)
init(mode: AppMode) {
switch (mode) {
default:
baseUrl = "https://amg-staging.herokuapp.com"
}
}
private func buildRequest(endpoint: String, params: [String: String], method: String, handler: @escaping (Data?, URLResponse?, Error?) -> Void) {
guard let url = URL(string: "\(baseUrl)\(endpoint)") else {
print("VOService.buildRequest(): could not build url")
return
}
guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
print("VOService.buildRequest(): could not build url components")
return
}
var queryParams: [URLQueryItem] = []
for (key, value) in params {
queryParams.append(URLQueryItem(name: key, value: value))
}
components.queryItems = queryParams
var request = URLRequest(url: url)
request.httpMethod = method
request.httpBody = Data(components.url!.query!.utf8)
return URLSession.shared.dataTask(with: request, completionHandler: handler).resume()
}
public func login(email: String, password: String, handler: @escaping (Data?, URLResponse?, Error?) -> Void) {
let params = ["email": email, "password": password]
buildRequest(endpoint: "/auth/sign_in", params: params, method: "POST", handler: handler)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment