-
Notifications
You must be signed in to change notification settings - Fork 1
/
ViewController.swift
98 lines (73 loc) · 3.03 KB
/
ViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
//
// ViewController.swift
// StormViewer
//
// Created by Julian Moorhouse on 04/07/2019.
// Copyright © 2019 Mindwarp Consultancy Ltd. All rights reserved.
//
import UIKit
class ViewController: UITableViewController {
var storms = [Storm]()
override func viewDidLoad() {
super.viewDidLoad()
title = "Storm Viewer"
navigationController?.navigationBar.prefersLargeTitles = true
performSelector(inBackground: #selector(loadImages), with: nil)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return storms.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Picture", for: indexPath)
let views = storms[indexPath.row].viewCount
cell.textLabel?.text = storms[indexPath.row].pictureName
cell.detailTextLabel?.text = views > 0 ? "Views: \(views)" : ""
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let vc = storyboard?.instantiateViewController(withIdentifier: "Detail") as? DetailViewController {
vc.selectedImage = storms[indexPath.row].pictureName
vc.selectedPictureNumber = indexPath.row + 1
vc.totalPictures = storms.count
storms[indexPath.row].viewCount += 1
save()
tableView.performSelector(onMainThread: #selector(UITableView.reloadData), with: nil, waitUntilDone: false)
navigationController?.pushViewController(vc, animated: true)
}
}
@objc func loadImages() {
let fm = FileManager.default
let path = Bundle.main.resourcePath!
let items = try! fm.contentsOfDirectory(atPath: path)
for item in items {
if item.hasPrefix("nssl") {
// this is a picture to load!
storms.append(Storm(pictureName: item, viewCount: 0))
}
}
load()
//storms.sort()
print(storms)
tableView.performSelector(onMainThread: #selector(UITableView.reloadData), with: nil, waitUntilDone: false)
}
func save() {
let jsonEncoder = JSONEncoder()
if let savedDate = try? jsonEncoder.encode(storms) {
let defaults = UserDefaults.standard
defaults.set(savedDate, forKey: "storms")
} else {
print("Failed to save storms")
}
}
func load() {
let defaults = UserDefaults.standard
if let savedStorms = defaults.object(forKey: "storms") as? Data {
let jsonDecoder = JSONDecoder()
do {
storms = try jsonDecoder.decode([Storm].self, from: savedStorms)
} catch {
print("Failed to load storms.")
}
}
}
}