Created
August 1, 2018 19:40
-
-
Save vialyx/e3fff6f984f02ca7f2a79a0bd2398346 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ViewController.swift | |
// AirportTimeTable | |
// | |
// Created by Maksim Vialykh on 01.08.2018. | |
// Copyright © 2018 Vialyx. All rights reserved. | |
// | |
import UIKit | |
class ViewController: UIViewController { | |
// TODO: - Inject it from outside | |
lazy var model: ModelInput! = { [unowned self] in | |
let model = Model() | |
model.output = self | |
return model | |
}() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
model.load() | |
} | |
override func didReceiveMemoryWarning() { | |
super.didReceiveMemoryWarning() | |
// Dispose of any resources that can be recreated. | |
} | |
} | |
// MARK: - ModelOutput | |
extension ViewController: ModelOutput { | |
func modelDidLoad() { | |
print("modelDidLoad with items: \(model.items)") | |
} | |
func modelDidFail(error: Error?) { | |
print("modelDidFail with error: \(String(describing: error))") | |
} | |
} | |
// FIXME: - Move out Model to the separated .swift file | |
struct Data: Codable { | |
let company_name: String | |
let departure_time: String | |
let flight: String | |
let direction: String | |
let reseption: String | |
let gate: String | |
let status: String | |
} | |
protocol ModelInput { | |
var items: [Data] { get } | |
func load() | |
} | |
protocol ModelOutput: class { | |
func modelDidLoad() | |
func modelDidFail(error: Error?) | |
} | |
final class Model: ModelInput { | |
private (set) var items: [Data] = [] | |
weak var output: ModelOutput! | |
func load() { | |
let url = URL(string: "http://localhost:8080/departure")! | |
let request = URLRequest(url: url) | |
let task = URLSession.shared.dataTask(with: request) { [weak self] (data, response, error) in | |
guard let `data` = data else { | |
self?.output.modelDidFail(error: error) | |
return | |
} | |
do { | |
self?.items = try JSONDecoder().decode([Data].self, from: data) | |
self?.output.modelDidLoad() | |
} catch { | |
self?.output.modelDidFail(error: error) | |
} | |
} | |
task.resume() | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment