Skip to content

Commit a173d00

Browse files
committed
Рефактор
Заменил fatalErrors на doCatch блоки
1 parent 7421031 commit a173d00

File tree

7 files changed

+90
-51
lines changed

7 files changed

+90
-51
lines changed

SwiftUI-WorkoutApp/Extensions/Bundle+.swift

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@ extension Bundle {
66
fileName : String,
77
dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .deferredToDate,
88
keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys
9-
) -> T {
9+
) throws -> T {
1010
guard let url = self.url(forResource: fileName, withExtension: nil) else {
11-
fatalError("Не удалось загрузить файл: \(fileName)")
11+
throw BundleError.cannotLoad(fileName)
1212
}
1313
do {
1414
let jsonData = try Data(contentsOf: url)
@@ -18,7 +18,21 @@ extension Bundle {
1818
let result = try decoder.decode(type, from: jsonData)
1919
return result
2020
} catch {
21-
fatalError("Ошибка преобразования json: \(error)")
21+
throw BundleError.decodingError(error)
22+
}
23+
}
24+
25+
enum BundleError: Error, LocalizedError {
26+
case cannotLoad(_ fileName: String)
27+
case decodingError(_ error: Error)
28+
29+
var errorDescription: String? {
30+
switch self {
31+
case let .cannotLoad(fileName):
32+
return "Не удалось загрузить файл: \(fileName)"
33+
case let .decodingError(error):
34+
return "Ошибка преобразования json: \(error)"
35+
}
2236
}
2337
}
2438
}

SwiftUI-WorkoutApp/Models/EventResponse.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ extension EventResponse {
116116
.init(id: .zero, title: nil, eventDescription: nil, fullAddress: nil, createDate: nil, modifyDate: nil, beginDate: nil, countryID: nil, cityID: nil, commentsCount: nil, commentsOptional: nil, previewImageStringURL: nil, sportsGroundID: nil, latitude: nil, longitude: nil, participantsCount: nil, participantsOptional: nil, isCurrent: nil, photos: nil, authorName: nil, author: nil, trainHereOptional: nil)
117117
}
118118
static var mock: EventResponse {
119-
Bundle.main.decodeJson(
119+
try! Bundle.main.decodeJson(
120120
[EventResponse].self,
121121
fileName: "oldEvents.json"
122122
).first!

SwiftUI-WorkoutApp/Models/SportsGround.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ extension SportsGround {
165165
.init(id: .zero, typeID: .zero, sizeID: .zero, address: nil, author: .emptyValue, cityID: nil, commentsCount: nil, countryID: nil, createDate: nil, modifyDate: nil, latitude: "", longitude: "", name: nil, photos: [], preview: nil, usersTrainHereCount: .zero, commentsOptional: nil, usersTrainHere: [], trainHere: nil)
166166
}
167167
static var mock: SportsGround {
168-
Bundle.main.decodeJson(
168+
try! Bundle.main.decodeJson(
169169
[SportsGround].self,
170170
fileName: "oldSportsGrounds.json"
171171
).first!

SwiftUI-WorkoutApp/Screens/Events/List/EventsListViewModel.swift

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,6 @@ final class EventsListViewModel: ObservableObject {
66
@Published var pastEvents = [EventResponse]()
77
@Published private(set) var isLoading = false
88
@Published private(set) var errorMessage = ""
9-
private let oldEvents = Bundle.main.decodeJson(
10-
[EventResponse].self,
11-
fileName: "oldEvents.json"
12-
)
139

1410
func askForEvents(type: EventType, refresh: Bool, with defaults: DefaultsService) async {
1511
if isLoading && !refresh
@@ -25,7 +21,7 @@ final class EventsListViewModel: ObservableObject {
2521
}
2622
} catch {
2723
if type == .past {
28-
pastEvents = oldEvents
24+
setupOldEventsFromBundle()
2925
}
3026
errorMessage = error.localizedDescription
3127
}
@@ -34,3 +30,17 @@ final class EventsListViewModel: ObservableObject {
3430

3531
func clearErrorMessage() { errorMessage = "" }
3632
}
33+
34+
private extension EventsListViewModel {
35+
func setupOldEventsFromBundle() {
36+
do {
37+
let oldEvents = try Bundle.main.decodeJson(
38+
[EventResponse].self,
39+
fileName: "oldEvents.json"
40+
)
41+
pastEvents = oldEvents
42+
} catch {
43+
errorMessage = error.localizedDescription
44+
}
45+
}
46+
}

SwiftUI-WorkoutApp/Screens/SportsGrounds/Map/SportsGroundsMapViewModel.swift

Lines changed: 22 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,7 @@ final class SportsGroundsMapViewModel: NSObject, ObservableObject {
55
private let manager = CLLocationManager()
66
private var userCountryID = Int.zero
77
private var userCityID = Int.zero
8-
private var defaultList = Bundle.main.decodeJson(
9-
[SportsGround].self,
10-
fileName: "oldSportsGrounds.json"
11-
)
8+
private var defaultList = [SportsGround]()
129
@Published private(set) var isLoading = false
1310
@Published private(set) var errorMessage = ""
1411
@Published var filter = SportsGroundFilter() {
@@ -28,18 +25,20 @@ final class SportsGroundsMapViewModel: NSObject, ObservableObject {
2825
}
2926

3027
func makeGrounds(refresh: Bool, with defaults: DefaultsService) async {
31-
if (isLoading || !list.isEmpty) && !refresh { return }
32-
if list.isEmpty {
28+
if (isLoading || !defaultList.isEmpty) && !refresh { return }
29+
if defaultList.isEmpty {
30+
fillDefaultList()
3331
applyFilter(defaults.mainUserCountry, defaults.mainUserCity)
3432
return
3533
}
3634
isLoading.toggle()
3735
do {
3836
defaultList = try await APIService(with: defaults).getAllSportsGrounds()
39-
applyFilter(defaults.mainUserCountry, defaults.mainUserCity)
4037
} catch {
38+
fillDefaultList()
4139
errorMessage = error.localizedDescription
4240
}
41+
applyFilter(defaults.mainUserCountry, defaults.mainUserCity)
4342
isLoading.toggle()
4443
}
4544

@@ -127,10 +126,6 @@ extension SportsGroundsMapViewModel: CLLocationManagerDelegate {
127126
didFailWithError error: Error
128127
) {
129128
errorMessage = error.localizedDescription
130-
#if DEBUG
131-
print("locationManager didFailWithError")
132-
print(error)
133-
#endif
134129
}
135130
}
136131

@@ -141,18 +136,27 @@ private extension SportsGroundsMapViewModel {
141136
filter.size.map { $0.code }.contains(ground.sizeID)
142137
&& filter.type.map { $0.code }.contains(ground.typeID)
143138
}
144-
guard countryID != .zero else {
139+
guard countryID != .zero, filter.onlyMyCity else {
145140
list = result
146141
needUpdateAnnotations.toggle()
147142
return
148143
}
149-
if filter.onlyMyCity {
150-
result = result.filter {
151-
$0.countryID == countryID
152-
&& $0.cityID == cityID
153-
}
144+
list = result.filter {
145+
$0.countryID == countryID
146+
&& $0.cityID == cityID
154147
}
155-
list = result
156148
needUpdateAnnotations.toggle()
157149
}
150+
151+
func fillDefaultList() {
152+
do {
153+
let oldGrounds = try Bundle.main.decodeJson(
154+
[SportsGround].self,
155+
fileName: "oldSportsGrounds.json"
156+
)
157+
defaultList = oldGrounds
158+
} catch {
159+
errorMessage = error.localizedDescription
160+
}
161+
}
158162
}

SwiftUI-WorkoutApp/Screens/Welcome/Account/AccountInfoViewModel.swift

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import Foundation
2+
import CoreLocation
23

34
@MainActor
45
final class AccountInfoViewModel: ObservableObject {
@@ -70,18 +71,25 @@ final class AccountInfoViewModel: ObservableObject {
7071

7172
private extension AccountInfoViewModel {
7273
func makeCountryAndCityData() {
73-
let _countries = Bundle.main.decodeJson(
74-
[Country].self,
75-
fileName: "countries.json"
76-
)
77-
guard let russia = _countries.first(where: { $0.name == "Россия" }),
78-
let moscow = russia.cities.first(where: { $0.name == "Москва" }) else {
79-
fatalError("Россия и Москва должны быть в файле countries.json")
74+
do {
75+
let allCountries = try Bundle.main.decodeJson(
76+
[Country].self,
77+
fileName: "countries.json"
78+
)
79+
if let russia = allCountries.first(where: { $0.name == "Россия" }),
80+
let moscow = russia.cities.first(where: { $0.name == "Москва" }) {
81+
countries = allCountries.sorted { $0.name < $1.name }
82+
userForm.country = russia
83+
cities = russia.cities.sorted { $0.name < $1.name }
84+
userForm.city = moscow
85+
} else {
86+
#if DEBUG
87+
print("--- Россия и Москва должны быть в файле countries.json")
88+
#endif
89+
}
90+
} catch {
91+
errorMessage = error.localizedDescription
8092
}
81-
countries = _countries.sorted { $0.name < $1.name }
82-
userForm.country = russia
83-
cities = russia.cities.sorted { $0.name < $1.name }
84-
userForm.city = moscow
8593
}
8694

8795
func updateCityIfNeeded(for country: Country) {
Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,22 @@
11
import Foundation
22

33
struct ShortAddressService {
4-
private let countries = Bundle.main.decodeJson(
5-
[Country].self,
6-
fileName: "countries.json"
7-
)
8-
94
func addressFor(_ countryID: Int, _ cityID: Int) -> String {
10-
let country = countries.first(where: { $0.id == String(countryID) })
11-
let city = country?.cities.first(where: { $0.id == String(cityID) })
12-
let countryName = (country?.name).valueOrEmpty
13-
if let cityName = city?.name {
14-
return countryName + ", " + cityName
15-
} else {
16-
return countryName
5+
do {
6+
let countries = try Bundle.main.decodeJson(
7+
[Country].self,
8+
fileName: "countries.json"
9+
)
10+
let country = countries.first(where: { $0.id == String(countryID) })
11+
let city = country?.cities.first(where: { $0.id == String(cityID) })
12+
let countryName = (country?.name).valueOrEmpty
13+
if let cityName = city?.name {
14+
return countryName + ", " + cityName
15+
} else {
16+
return countryName
17+
}
18+
} catch {
19+
return ""
1720
}
1821
}
1922
}

0 commit comments

Comments
 (0)