Skip to content

Instantly share code, notes, and snippets.

@vialyx
Created April 1, 2020 15:30
Show Gist options
  • Save vialyx/c84ce8e77e7650ba57f5234a189125ab to your computer and use it in GitHub Desktop.
Save vialyx/c84ce8e77e7650ba57f5234a189125ab to your computer and use it in GitHub Desktop.
import UIKit
import PlaygroundSupport
// API CLient
typealias Resource = (url: String, method: String, data: Data)
class APIClient {
func request(_ res: Resource, _ result: @escaping (Result<Data, Error>) -> Void) {
/*
All network code
- request
- task
- data retrivement
*/
result(Result.success("505".data(using: .utf8)!))
}
}
// Storage
struct User: Codable {
let id: String
let un: String
let pw: String
}
enum RepoError: Error {
case decoding
}
class UserRepo {
private let apiClient = APIClient()
func signup(_ user: User, _ result: @escaping (Result<Int, Error>) -> Void) {
let resource = Resource("https://...", "POST", try! JSONEncoder().encode(user))
apiClient.request(resource) { (res) in
switch res {
case .success(let data):
guard let id = try? JSONDecoder().decode(Int.self, from: data) else {
result(.failure(RepoError.decoding))
return
}
result(.success(id))
case .failure(let err):
result(.failure(err))
}
}
}
// e.g.
func getUser(_ id: Int, _ result: @escaping (Result<User, Error>) -> Void) {
// TODO: - implement
/*
- get from DB
- perform request to the server using APIClient
*/
}
}
// Logic
typealias SignUpResult = (Error?) -> Void
class RegModel {
let repository = UserRepo()
func validate(un: String?, pw: String?) throws {
// Validate input data
}
func signup(un: String?, pw: String?, _ result: @escaping SignUpResult) {
let user = User(id: "0", un: un!, pw: pw!)
repository.signup(user) { (res) in
switch res {
case .success(let id):
// - create a new one User struct with received id and store into local storage
result(nil)
case .failure(let err):
result(err)
}
}
}
}
// View & Controller
class RegVC: UIViewController {
private let model = RegModel()
@IBAction func signup() {
// 1 - validation
let un: String = "", pw: String = ""
do {
try model.validate(un: un, pw: pw)
} catch {
// Display error e.g. UIAlertController
return
}
// 2 - Registration
// ->>>> SHOW HUD (ActivityIndicator)
model.signup(un: un, pw: pw) { (err) in
// - >>> HIDE HUD
if err != nil {
// Display error e.g. UIAlertController
} else {
// Navigate to the next screen
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment