-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDataStorage.swift
103 lines (77 loc) · 2.84 KB
/
DataStorage.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
98
99
100
101
102
103
//
// ViewController.swift
// TestProj
//
// Created by LEONG YI MEI on 03/08/2021.
//
import UIKit
struct Character: Codable {
var name: String = ""
var level: Int = 0
}
class ViewController: UIViewController {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var levelLabel: UILabel!
@IBOutlet weak var usernameLabel: UILabel!
var cloud = Character()
var username: String = ""
//Characterpath
let characterFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("character.plist")
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
loadCharacter()
username = UserDefaults.standard.object(forKey: "username") as? String ?? "-"
usernameLabel.text = "Welcome, " + username
}
@IBAction func spawnButtonTapped(_ sender: Any) {
cloud.name = "Cloud"
cloud.level = 5
nameLabel.text = cloud.name
levelLabel.text = String(cloud.level)
let xmlData = try? PropertyListEncoder().encode(cloud)
if xmlData != nil {
if FileManager.default.fileExists(atPath: characterFilePath.path) {
//File exists
try? xmlData!.write(to: characterFilePath)
}
else {
FileManager.default.createFile(atPath: characterFilePath.path, contents: xmlData, attributes: nil)
}
}
}
func loadCharacter() {
let xmlData = try? Data(contentsOf: characterFilePath)
if xmlData != nil {
let loadedCharacter = try? PropertyListDecoder().decode(Character.self, from: xmlData!)
if loadedCharacter != nil {
cloud = loadedCharacter!
nameLabel.text = cloud.name
levelLabel.text = String(cloud.level)
}
}
}
@IBAction func levelUpButtonTapped(_ sender: Any) {
cloud.level += 1
levelLabel.text = String(cloud.level)
let xmlData = try? PropertyListEncoder().encode(cloud)
if xmlData != nil {
if FileManager.default.fileExists(atPath: characterFilePath.path) {
try? xmlData!.write(to: characterFilePath)
}
else {
FileManager.default.createFile(atPath: characterFilePath.path, contents: xmlData, attributes: nil)
}
}
}
@IBAction func loginButtonTapped(_ sender: Any) {
username = "John Appleseed"
usernameLabel.text = "Welcome, " + username
UserDefaults.standard.setValue(username, forKey: "username")
}
@IBAction func logoutButtonPressed(_ sender: Any) {
username = ""
usernameLabel.text = "Welcome, " + username
UserDefaults.standard.removeObject(forKey: "username")
}
}