feature/ios-app/core-data #56

Manually merged
Ghost merged 14 commits from feature/ios-app/core-data into master 2020-01-29 13:09:24 +01:00
19 changed files with 979 additions and 28 deletions
+60 -8
View File
@@ -51,7 +51,6 @@
9E9F89F623D86B3A0014CE69 /* DateExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E9F89F523D86B3A0014CE69 /* DateExtensions.swift */; };
9E9F89FA23D899060014CE69 /* StringExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E9F89F923D899060014CE69 /* StringExtensions.swift */; };
9E9F89FC23D899390014CE69 /* PropertyKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E9F89FB23D899390014CE69 /* PropertyKey.swift */; };
9E9F8A0223D89CCA0014CE69 /* Devices.xcdatamodeld in Sources */ = {isa = PBXBuildFile; fileRef = 9E9F8A0023D89CCA0014CE69 /* Devices.xcdatamodeld */; };
9E9F8A0923D8A1430014CE69 /* MeasurementAll.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E9F8A0823D8A1430014CE69 /* MeasurementAll.swift */; };
9E9F8A0D23D8AEA30014CE69 /* Day.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E9F8A0C23D8AEA30014CE69 /* Day.swift */; };
9E9F8A0F23D8B2A10014CE69 /* MeasurementDay.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E9F8A0E23D8B2A10014CE69 /* MeasurementDay.swift */; };
@@ -76,9 +75,21 @@
9EFDEF9A23C215A9006EB4B4 /* AlertFactory.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EFDEF9923C215A9006EB4B4 /* AlertFactory.swift */; };
BC04DC0B23CB3BE7006D0767 /* FavoriteSearch.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC04DC0A23CB3BE7006D0767 /* FavoriteSearch.swift */; };
BC04DC0D23CB4104006D0767 /* FavoriteSearchResultRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC04DC0C23CB4104006D0767 /* FavoriteSearchResultRow.swift */; };
BC11C1B923DF07FC008F9E7A /* CDLocation+CoreDataClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC11C1B723DF07FC008F9E7A /* CDLocation+CoreDataClass.swift */; };
BC11C1BA23DF07FC008F9E7A /* CDLocation+CoreDataProperties.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC11C1B823DF07FC008F9E7A /* CDLocation+CoreDataProperties.swift */; };
BC11C1BE23DF0ABD008F9E7A /* CDNamesDictionary+CoreDataClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC11C1BC23DF0ABD008F9E7A /* CDNamesDictionary+CoreDataClass.swift */; };
BC11C1BF23DF0ABD008F9E7A /* CDNamesDictionary+CoreDataProperties.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC11C1BD23DF0ABD008F9E7A /* CDNamesDictionary+CoreDataProperties.swift */; };
BC11C1C123DF2F79008F9E7A /* FavoriteDetail.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC11C1C023DF2F79008F9E7A /* FavoriteDetail.swift */; };
BC11C1C323DF3851008F9E7A /* FavoriteHeaderView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC11C1C223DF3851008F9E7A /* FavoriteHeaderView.swift */; };
BC11C1C523DF411B008F9E7A /* FavoriteTodayView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC11C1C423DF411B008F9E7A /* FavoriteTodayView.swift */; };
BC11C1C723DF4868008F9E7A /* FavoritesNextDaysView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC11C1C623DF4868008F9E7A /* FavoritesNextDaysView.swift */; };
BC11C1C923DF776F008F9E7A /* FavoriteNextDaysDayView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC11C1C823DF776F008F9E7A /* FavoriteNextDaysDayView.swift */; };
BC1A86B723CBB755005DE4F5 /* LocationHeaderView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC1A86B623CBB755005DE4F5 /* LocationHeaderView.swift */; };
BC241EC323CB8B0600F4C0CC /* FavoriteCity.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC241EC223CB8B0600F4C0CC /* FavoriteCity.swift */; };
BC26444123CB835300330645 /* WeatherConditionExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC26444023CB835300330645 /* WeatherConditionExtension.swift */; };
BC71C16F23D9B7B800BBA56E /* NewFavoriteLocations.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC71C16E23D9B7B800BBA56E /* NewFavoriteLocations.swift */; };
BC90508023DB315500414C73 /* Mowesta.xcdatamodeld in Sources */ = {isa = PBXBuildFile; fileRef = BC90507E23DB315500414C73 /* Mowesta.xcdatamodeld */; };
BC90508223DB451D00414C73 /* FavoriteListItemView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC90508123DB451D00414C73 /* FavoriteListItemView.swift */; };
BCEE929023CCEDD80029CC73 /* LocationDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BCEE928F23CCEDD80029CC73 /* LocationDetailView.swift */; };
BCEE929223CCF7B60029CC73 /* LocationForecastView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BCEE929123CCF7B60029CC73 /* LocationForecastView.swift */; };
BCFAD1F923CB4BEC0032455B /* FavoriteSearchResults.swift in Sources */ = {isa = PBXBuildFile; fileRef = BCFAD1F823CB4BEC0032455B /* FavoriteSearchResults.swift */; };
@@ -152,7 +163,6 @@
9E9F89F523D86B3A0014CE69 /* DateExtensions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DateExtensions.swift; sourceTree = "<group>"; };
9E9F89F923D899060014CE69 /* StringExtensions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StringExtensions.swift; sourceTree = "<group>"; };
9E9F89FB23D899390014CE69 /* PropertyKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PropertyKey.swift; sourceTree = "<group>"; };
9E9F8A0123D89CCA0014CE69 /* Devices.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = Devices.xcdatamodel; sourceTree = "<group>"; };
9E9F8A0823D8A1430014CE69 /* MeasurementAll.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeasurementAll.swift; sourceTree = "<group>"; };
9E9F8A0C23D8AEA30014CE69 /* Day.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Day.swift; sourceTree = "<group>"; };
9E9F8A0E23D8B2A10014CE69 /* MeasurementDay.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeasurementDay.swift; sourceTree = "<group>"; };
@@ -177,9 +187,21 @@
9EFDEF9923C215A9006EB4B4 /* AlertFactory.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AlertFactory.swift; sourceTree = "<group>"; };
BC04DC0A23CB3BE7006D0767 /* FavoriteSearch.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FavoriteSearch.swift; sourceTree = "<group>"; };
BC04DC0C23CB4104006D0767 /* FavoriteSearchResultRow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FavoriteSearchResultRow.swift; sourceTree = "<group>"; };
BC11C1B723DF07FC008F9E7A /* CDLocation+CoreDataClass.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CDLocation+CoreDataClass.swift"; sourceTree = "<group>"; };
BC11C1B823DF07FC008F9E7A /* CDLocation+CoreDataProperties.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CDLocation+CoreDataProperties.swift"; sourceTree = "<group>"; };
BC11C1BC23DF0ABD008F9E7A /* CDNamesDictionary+CoreDataClass.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CDNamesDictionary+CoreDataClass.swift"; sourceTree = "<group>"; };
BC11C1BD23DF0ABD008F9E7A /* CDNamesDictionary+CoreDataProperties.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CDNamesDictionary+CoreDataProperties.swift"; sourceTree = "<group>"; };
BC11C1C023DF2F79008F9E7A /* FavoriteDetail.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FavoriteDetail.swift; sourceTree = "<group>"; };
BC11C1C223DF3851008F9E7A /* FavoriteHeaderView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FavoriteHeaderView.swift; sourceTree = "<group>"; };
BC11C1C423DF411B008F9E7A /* FavoriteTodayView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FavoriteTodayView.swift; sourceTree = "<group>"; };
BC11C1C623DF4868008F9E7A /* FavoritesNextDaysView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FavoritesNextDaysView.swift; sourceTree = "<group>"; };
BC11C1C823DF776F008F9E7A /* FavoriteNextDaysDayView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FavoriteNextDaysDayView.swift; sourceTree = "<group>"; };
BC1A86B623CBB755005DE4F5 /* LocationHeaderView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocationHeaderView.swift; sourceTree = "<group>"; };
BC241EC223CB8B0600F4C0CC /* FavoriteCity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FavoriteCity.swift; sourceTree = "<group>"; };
BC26444023CB835300330645 /* WeatherConditionExtension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WeatherConditionExtension.swift; sourceTree = "<group>"; };
BC71C16E23D9B7B800BBA56E /* NewFavoriteLocations.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewFavoriteLocations.swift; sourceTree = "<group>"; };
BC90507F23DB315500414C73 /* Mowesta.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = Mowesta.xcdatamodel; sourceTree = "<group>"; };
BC90508123DB451D00414C73 /* FavoriteListItemView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FavoriteListItemView.swift; sourceTree = "<group>"; };
BCEE928F23CCEDD80029CC73 /* LocationDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocationDetailView.swift; sourceTree = "<group>"; };
BCEE929123CCF7B60029CC73 /* LocationForecastView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocationForecastView.swift; sourceTree = "<group>"; };
BCFAD1F823CB4BEC0032455B /* FavoriteSearchResults.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FavoriteSearchResults.swift; sourceTree = "<group>"; };
@@ -249,6 +271,7 @@
2C7846D32372F44300766694 /* app */ = {
isa = PBXGroup;
children = (
BC11C1BB23DF0862008F9E7A /* CoreData */,
9E9F89F823D898F50014CE69 /* Extensions */,
9E6D640423CC73320002CBCF /* MoWeSta.entitlements */,
9E0C988623A78331001EA11E /* Data */,
@@ -264,7 +287,6 @@
9E3CA40223A53A2E003873E8 /* Resources */,
2CDF8C6D2372FA9500080243 /* WebScreen.storyboard */,
9E37A1E223C9CF4200A80652 /* Localizable.strings */,
9E9F8A0023D89CCA0014CE69 /* Devices.xcdatamodeld */,
);
path = app;
sourceTree = "<group>";
@@ -317,6 +339,12 @@
BC04DC0A23CB3BE7006D0767 /* FavoriteSearch.swift */,
BC04DC0C23CB4104006D0767 /* FavoriteSearchResultRow.swift */,
BCFAD1F823CB4BEC0032455B /* FavoriteSearchResults.swift */,
BC90508123DB451D00414C73 /* FavoriteListItemView.swift */,
BC11C1C023DF2F79008F9E7A /* FavoriteDetail.swift */,
BC11C1C223DF3851008F9E7A /* FavoriteHeaderView.swift */,
BC11C1C423DF411B008F9E7A /* FavoriteTodayView.swift */,
BC11C1C623DF4868008F9E7A /* FavoritesNextDaysView.swift */,
BC11C1C823DF776F008F9E7A /* FavoriteNextDaysDayView.swift */,
);
path = Favorite;
sourceTree = "<group>";
@@ -324,6 +352,7 @@
9E3CA40223A53A2E003873E8 /* Resources */ = {
isa = PBXGroup;
children = (
BC90507E23DB315500414C73 /* Mowesta.xcdatamodeld */,
);
path = Resources;
sourceTree = "<group>";
@@ -345,6 +374,7 @@
children = (
9EA0D16123C911790068F739 /* Mock */,
9EE4771923C3C77F003BA29C /* FavoriteLocations.swift */,
BC71C16E23D9B7B800BBA56E /* NewFavoriteLocations.swift */,
);
path = Environment;
sourceTree = "<group>";
@@ -525,6 +555,17 @@
path = OwnDevice;
sourceTree = "<group>";
};
BC11C1BB23DF0862008F9E7A /* CoreData */ = {
isa = PBXGroup;
children = (
BC11C1BC23DF0ABD008F9E7A /* CDNamesDictionary+CoreDataClass.swift */,
BC11C1BD23DF0ABD008F9E7A /* CDNamesDictionary+CoreDataProperties.swift */,
BC11C1B723DF07FC008F9E7A /* CDLocation+CoreDataClass.swift */,
BC11C1B823DF07FC008F9E7A /* CDLocation+CoreDataProperties.swift */,
);
path = CoreData;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
@@ -670,6 +711,7 @@
buildActionMask = 2147483647;
files = (
BC1A86B723CBB755005DE4F5 /* LocationHeaderView.swift in Sources */,
BC11C1B923DF07FC008F9E7A /* CDLocation+CoreDataClass.swift in Sources */,
9EA0D16323C9118C0068F739 /* LocationMock.swift in Sources */,
BCEE929023CCEDD80029CC73 /* LocationDetailView.swift in Sources */,
9E6D640D23CC798F0002CBCF /* WSPairRow.swift in Sources */,
@@ -677,10 +719,12 @@
9EE4770C23C36363003BA29C /* SearchResults.swift in Sources */,
2C7846D52372F44300766694 /* AppDelegate.swift in Sources */,
9E6D640F23CC7BBD0002CBCF /* Register.swift in Sources */,
BC11C1BE23DF0ABD008F9E7A /* CDNamesDictionary+CoreDataClass.swift in Sources */,
9E3CA3EF23A51DFC003873E8 /* DegreeNumberCircle.swift in Sources */,
9E2CB4AC23CF5DB6009F0C9E /* MeasurementService.swift in Sources */,
9E6D640B23CC77800002CBCF /* AboutMe.swift in Sources */,
9EA8C18C23D1FFB200E54919 /* SwaggerAPI.swift in Sources */,
BC11C1C923DF776F008F9E7A /* FavoriteNextDaysDayView.swift in Sources */,
9E81DC9223A7DECE00568CF4 /* UserData.swift in Sources */,
BC04DC0B23CB3BE7006D0767 /* FavoriteSearch.swift in Sources */,
9EEAF94D23C1F3DC000AAB49 /* SearchTab.swift in Sources */,
@@ -689,6 +733,7 @@
9E9F89FA23D899060014CE69 /* StringExtensions.swift in Sources */,
BC241EC323CB8B0600F4C0CC /* FavoriteCity.swift in Sources */,
9E86187E23D2254F00957CBE /* ActivityIndicator.swift in Sources */,
BC11C1C123DF2F79008F9E7A /* FavoriteDetail.swift in Sources */,
2C7846D72372F44300766694 /* SceneDelegate.swift in Sources */,
9EA6239223D5C8E900BFA8B9 /* AltimeterService.swift in Sources */,
9EE4771423C37158003BA29C /* SearchResultRow.swift in Sources */,
@@ -699,22 +744,29 @@
9E78A74C23C91B4A00D8A27D /* CountryDetail.swift in Sources */,
9E86187823D21F8400957CBE /* OwnDeviceRow.swift in Sources */,
9E0F1CD223D1ED1300329FC6 /* DeviceData.swift in Sources */,
BC90508223DB451D00414C73 /* FavoriteListItemView.swift in Sources */,
BC11C1C323DF3851008F9E7A /* FavoriteHeaderView.swift in Sources */,
9E86187023D2163A00957CBE /* Devices.swift in Sources */,
9EFDEF9A23C215A9006EB4B4 /* AlertFactory.swift in Sources */,
BC11C1BF23DF0ABD008F9E7A /* CDNamesDictionary+CoreDataProperties.swift in Sources */,
9EEAF94E23C1F3DC000AAB49 /* SearchBar.swift in Sources */,
9E6D641423CCD2080002CBCF /* WSPairView.swift in Sources */,
9EE4770E23C363F6003BA29C /* ViewExtensions.swift in Sources */,
9E78A74A23C91B3D00D8A27D /* StateDetail.swift in Sources */,
BC71C16F23D9B7B800BBA56E /* NewFavoriteLocations.swift in Sources */,
9E8334A423AD003E00B191A3 /* Login.swift in Sources */,
BCEE929223CCF7B60029CC73 /* LocationForecastView.swift in Sources */,
9EE4771A23C3C77F003BA29C /* FavoriteLocations.swift in Sources */,
BC11C1BA23DF07FC008F9E7A /* CDLocation+CoreDataProperties.swift in Sources */,
2C7846D92372F44300766694 /* ContentView.swift in Sources */,
9E3CA3F423A52ABF003873E8 /* FavoriteList.swift in Sources */,
9EB08D8A23DC7A20004AFE51 /* Account.swift in Sources */,
9E6D641623CCDF900002CBCF /* Error.swift in Sources */,
9E6D640323CC730D0002CBCF /* WeatherStationPairingService.swift in Sources */,
9E9F8A0223D89CCA0014CE69 /* Devices.xcdatamodeld in Sources */,
9E3CA3F123A5278E003873E8 /* FavoriteRow.swift in Sources */,
BC11C1C523DF411B008F9E7A /* FavoriteTodayView.swift in Sources */,
BC11C1C723DF4868008F9E7A /* FavoritesNextDaysView.swift in Sources */,
BC90508023DB315500414C73 /* Mowesta.xcdatamodeld in Sources */,
9E78A74823C918C600D8A27D /* CityDetail.swift in Sources */,
9E9F89FC23D899390014CE69 /* PropertyKey.swift in Sources */,
9EB08D8423DC56A6004AFE51 /* DeviceOsExtension.swift in Sources */,
@@ -1127,13 +1179,13 @@
/* End XCSwiftPackageProductDependency section */
/* Begin XCVersionGroup section */
9E9F8A0023D89CCA0014CE69 /* Devices.xcdatamodeld */ = {
BC90507E23DB315500414C73 /* Mowesta.xcdatamodeld */ = {
isa = XCVersionGroup;
children = (
9E9F8A0123D89CCA0014CE69 /* Devices.xcdatamodel */,
BC90507F23DB315500414C73 /* Mowesta.xcdatamodel */,
);
currentVersion = 9E9F8A0123D89CCA0014CE69 /* Devices.xcdatamodel */;
path = Devices.xcdatamodeld;
currentVersion = BC90507F23DB315500414C73 /* Mowesta.xcdatamodel */;
path = Mowesta.xcdatamodeld;
sourceTree = "<group>";
versionGroupType = wrapper.xcdatamodel;
};
+48
View File
@@ -7,6 +7,7 @@
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
@@ -15,6 +16,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
// Override point for customization after application launch.
NSLog("didLaunchApplication")
MeasurementService.shared.registerMeasurementBGService()
//let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
//print(urls[urls.count-1] as URL)
return true
}
@@ -31,4 +34,49 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
NSLog("user discards scene session");
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Mowesta")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
@@ -0,0 +1,16 @@
//
// CDLocation+CoreDataClass.swift
// app
//
// Created by Tobias Stottrop on 27.01.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
//
import Foundation
import CoreData
@objc(CDLocation)
public class CDLocation: NSManagedObject {
}
@@ -0,0 +1,81 @@
//
// CDLocation+CoreDataProperties.swift
// app
//
// Created by Tobias Stottrop on 27.01.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
//
import Foundation
import CoreData
extension CDLocation {
@nonobjc public class func fetchRequest() -> NSFetchRequest<CDLocation> {
return NSFetchRequest<CDLocation>(entityName: "CDLocation")
}
@NSManaged public var capital: Bool
@NSManaged public var creationTime: Int64
@NSManaged public var id: Int64
@NSManaged public var markedDeleted: Bool
@NSManaged public var modificationTime: Int64
@NSManaged public var population: Int64
@NSManaged public var timezone: String?
@NSManaged public var type: String?
@NSManaged public var wikipedia: String?
@NSManaged public var coordinate: CDCoordinate?
@NSManaged public var forecast: CDWeatherForecast?
@NSManaged public var names: Set<CDNamesDictionary>?
}
extension CDLocation {
public func getMillisecondsFromGMT() -> Double {
switch self.timezone {
case "Europe/Berlin":
return 3600 * 1000
default:
return 0
}
}
public func getName() -> String {
let lang = Locale.current.languageCode ?? "en"
return getNameWithPriority(prefferedLanguage: Language(rawValue: lang) ?? .DEFAULT)
}
private func getNameWithPriority(prefferedLanguage language: Language) -> String {
if let names = self.names {
for case let item as CDNamesDictionary in names {
if (item.key == language.rawValue) {return item.value!}
}
for case let item as CDNamesDictionary in names {
if (item.key == "en") {return item.value!}
}
for case let item as CDNamesDictionary in names {
if (item.key == "local") {return item.value!}
}
}
return "NA"
}
}
// MARK: Generated accessors for names
extension CDLocation {
@objc(addNamesObject:)
@NSManaged public func addToNames(_ value: CDNamesDictionary)
@objc(removeNamesObject:)
@NSManaged public func removeFromNames(_ value: CDNamesDictionary)
@objc(addNames:)
@NSManaged public func addToNames(_ values: NSSet)
@objc(removeNames:)
@NSManaged public func removeFromNames(_ values: NSSet)
}
@@ -0,0 +1,16 @@
//
// CDNamesDictionary+CoreDataClass.swift
// app
//
// Created by Tobias Stottrop on 27.01.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
//
import Foundation
import CoreData
@objc(CDNamesDictionary)
public class CDNamesDictionary: NSManagedObject {
}
@@ -0,0 +1,24 @@
//
// CDNamesDictionary+CoreDataProperties.swift
// app
//
// Created by Tobias Stottrop on 27.01.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
//
import Foundation
import CoreData
extension CDNamesDictionary {
@nonobjc public class func fetchRequest() -> NSFetchRequest<CDNamesDictionary> {
return NSFetchRequest<CDNamesDictionary>(entityName: "CDNamesDictionary")
}
@NSManaged public var key: String?
@NSManaged public var value: String?
@NSManaged public var location: CDLocation?
}
@@ -32,9 +32,12 @@ let condition = WeatherCondition(source: WeatherCondition.Source.cosmoEurope, ti
let weatherforecast = WeatherForecast(_id: 8022, creationTime: 1578852215818, modificationTime: 1578852215818, deleted: false, coordinate: Coordinate(latitude: 7.0243988037109375, longitude: 50.9375), source: WeatherForecast.Source.iconEurope, surfaceHeight: -0.02880859375, plantCoverage: 0, soilType: WeatherForecast.SoilType.clay, conditions: [condition])
func loadTestData() -> [City] {
return [essen, berlin];
}
let bonnMowestaFavorite = SavedMowestaFavorites(id: 13334, type: "CITY")
let bonnCDLocation = CDLocation()
let citiesData: [City] = loadTestData()
@@ -0,0 +1,258 @@
//
// NewFavoriteLocations.swift
// app
//
// Created by Tobias Stottrop on 23.01.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
import Foundation
import Combine
import MowestaApi
import SwiftUI
import CoreData
class NewFavoriteLocation: ObservableObject {
typealias MowestaState = MowestaApi.State
let objectWillChange = ObservableObjectPublisher()
static var shared: NewFavoriteLocation = NewFavoriteLocation()
private static var identifier: String = "com.mowesta.favorites"
private var currentPorcessedLocation: CDLocation?
let appDelegate = UIApplication.shared.delegate as! AppDelegate;
@Published var savedFavorites: [SavedMowestaFavorites] {
didSet {
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(savedFavorites) {
let defaults = UserDefaults.standard
defaults.set(encoded, forKey: NewFavoriteLocation.identifier)
}
}
}
init() {
guard let savedFavoritesInUserDefaults = try? UserDefaults.standard.object(forKey: NewFavoriteLocation.identifier) as? Data
else {
self.savedFavorites = []
return
}
let decoder = JSONDecoder()
guard let loadedUserData = try? decoder.decode([SavedMowestaFavorites].self, from: savedFavoritesInUserDefaults)
else {
self.savedFavorites = []
return
}
self.savedFavorites = loadedUserData
}
public func deleteLocation(_ location: CDLocation) {
let managedContext = appDelegate.persistentContainer.viewContext
managedContext.delete(location)
}
public func deleteLocation(_ location: LocationHierarchy) {
// TODO Delete on CD
guard let index = try? self.savedFavorites.firstIndex(where: {$0.id == location._id})
else {
return
}
self.deleteLocation(at: index)
}
public func update(_ location: CDLocation) {
WeatherAPI.getForecast(_id: location.id, completion: self.addWeatherForecast)
}
public func deleteLocation(at index: Int) {
self.savedFavorites.remove(at: index)
}
public func deleteLocation(at indexSet: IndexSet) {
self.savedFavorites.remove(atOffsets: indexSet)
}
public func move (from source: IndexSet, to destination: Int) {
self.savedFavorites.move(fromOffsets: source, toOffset: destination)
}
private func addLocation(city: City?, error: Error?) {
if (error != nil) {
//maybe handle
}
if (city != nil) {
let managedContext = appDelegate.persistentContainer.viewContext
let addloc = CDLocation(context: managedContext)
addloc.capital = city?.capital ?? false
addloc.creationTime = city?.creationTime ?? 0
addloc.id = city!._id!
addloc.markedDeleted = city?.deleted ?? false
addloc.modificationTime = city?.modificationTime ?? 0
addloc.population = Int64(city?.population ?? 0)
addloc.timezone = city?.timezone ?? "+0"
addloc.type = city!.type.rawValue
addloc.wikipedia = city?.wikipedia ?? ""
for (key, value) in city!.names {
createCDNamesDictionary(for: key, with: value, in: addloc)
}
do {
try managedContext.save()
currentPorcessedLocation = addloc
WeatherAPI.getForecast(_id: addloc.id, completion: self.addWeatherForecast)
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
}
private func createCDWeatherCondition(for condidtion: WeatherCondition, in forecast: CDWeatherForecast) -> CDWeatherCondition {
let managedContext = appDelegate.persistentContainer.viewContext
let cond = CDWeatherCondition(context: managedContext)
cond.cloudCoverage = condidtion.cloudCoverage
cond.cloudDepth = condidtion.cloudDepth
cond.duration = Int64(condidtion.duration)
cond.forecast = forecast
cond.hour = Int64(condidtion.hour)
cond.humidity = condidtion.humidity
cond.precipitation = condidtion.precipitation
cond.pressure = condidtion.pressure
cond.snowDepth = condidtion.snowDepth
cond.source = condidtion.source.rawValue
cond.temperature = condidtion.temperature
cond.time = condidtion.time
cond.type = condidtion.getWeatherTypeImageName()
cond.windDirection = condidtion.getWindDirectionImageName()
cond.windSpeed = condidtion.windSpeed
return cond
}
private func createCDNamesDictionary(for key: String, with value: String, in location: CDLocation) -> CDNamesDictionary {
let managedContext = appDelegate.persistentContainer.viewContext
let named = CDNamesDictionary(context: managedContext)
named.key = key
named.value = value
named.location = location
NSLog(named.description);
return named
}
private func addWeatherForecast(forecast: WeatherForecast?, error: Error?) {
if (error != nil) {
//maybe handle
}
if (forecast != nil) {
//get Context
let managedContext = appDelegate.persistentContainer.viewContext
let fore = CDWeatherForecast(context: managedContext)
fore.creationTime = forecast?.creationTime ?? 0
fore.id = forecast!._id!
fore.markedDeleted = forecast?.deleted ?? false
fore.modificationTime = forecast?.modificationTime ?? 0
fore.plantCoverage = forecast?.plantCoverage ?? 0
fore.soilType = forecast?.soilType.rawValue ?? ""
fore.source = forecast?.source.rawValue ?? ""
fore.surfaceHeight = forecast?.surfaceHeight ?? 0
fore.location = currentPorcessedLocation
currentPorcessedLocation?.forecast = fore
for condition in forecast!.conditions {
createCDWeatherCondition(for: condition, in: fore)
}
do {
try managedContext.save()
self.objectWillChange.send()
// NSLog(currentPorcessedLocation?.forecast?.conditions?.description ?? "")
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
}
private func addLocation(state: MowestaState?, error: Error?) {
if (error != nil) {
//maybe handle
}
if (state != nil) {
let managedContext = appDelegate.persistentContainer.viewContext
let addloc = CDLocation(context: managedContext)
addloc.capital = false
addloc.id = state!._id!
addloc.creationTime = state?.creationTime ?? 0
addloc.markedDeleted = state?.deleted ?? false
addloc.modificationTime = state?.modificationTime ?? 0
addloc.population = Int64(state?.population ?? 0)
addloc.timezone = state?.timezone ?? "+0"
addloc.type = "STATE"
addloc.wikipedia = state?.wikipedia ?? ""
do {
try managedContext.save()
currentPorcessedLocation = addloc
WeatherAPI.getForecast(_id: addloc.id, completion: self.addWeatherForecast)
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
}
public func toggleLocation(_ location: LocationHierarchy) {
NSLog("Toggle location with id: \(String(describing: location._id))")
if let index = savedFavorites.firstIndex(where: { $0.id == location._id}) {
// TODO Delete on CD
savedFavorites.remove(at: index)
} else {
switch location.type {
case LocationHierarchy.ModelType.city:
LocationAPI.getCity(_id: location._id!, completion: self.addLocation)
case LocationHierarchy.ModelType.state:
LocationAPI.getState(_id: location._id!, completion: self.addLocation)
case LocationHierarchy.ModelType.country:
break
}
savedFavorites.append(SavedMowestaFavorites(id: location._id!, type: location.type.rawValue))
}
}
public func toggleLocation(_ location: CDLocation) {
if let index = savedFavorites.firstIndex(where: { $0.id == location.id}) {
// TODO Delete on CD
savedFavorites.remove(at: index)
} else {
switch location.type {
case LocationHierarchy.ModelType.city.rawValue:
LocationAPI.getCity(_id: location.id, completion: self.addLocation)
case LocationHierarchy.ModelType.state.rawValue:
LocationAPI.getState(_id: location.id, completion: self.addLocation)
case LocationHierarchy.ModelType.country.rawValue: break
default:
break
}
savedFavorites.append(SavedMowestaFavorites(id: location.id, type: location.type!))
}
}
}
class SavedMowestaFavorites: Codable, Identifiable {
let id: Int64
let type: String
init(id: Int64, type: String) {
self.id = id
self.type = type
}
}
@@ -13,6 +13,20 @@ import SwiftUI
extension WeatherCondition {
public func getWindDirectionImageName() -> String {
switch self.windDirection {
case .unknown: return "questionmark"
case .north: return "arrow.up"
case .northEast: return "arrow.up.right"
case .east: return "arrow.right"
case .southEast: return "arrow.down.right"
case .south: return "arrow.down"
case .southWest: return "arrow.down.left"
case .west: return "arrow.left"
case .northWest: return "arrow.up.left"
}
}
public func getWeatherTypeImageName() -> String {
switch self.type {
case .unknown: return "questionmark"
@@ -1,10 +1,63 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="15702" systemVersion="19C57" minimumToolsVersion="Automatic" sourceLanguage="Swift" userDefinedModelVersionIdentifier="">
<entity name="Location" representedClassName="Location" syncable="YES" codeGenerationType="class">
<entity name="CDCoordinate" representedClassName="CDCoordinate" syncable="YES" codeGenerationType="class">
<attribute name="latitude" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>
<attribute name="longitude" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>
<relationship name="location" optional="YES" maxCount="1" deletionRule="Nullify" destinationEntity="CDLocation" inverseName="coordinate" inverseEntity="CDLocation"/>
</entity>
<entity name="CDLocation" representedClassName="CDLocation" syncable="YES">
<attribute name="capital" optional="YES" attributeType="Boolean" usesScalarValueType="YES"/>
<attribute name="creationTime" optional="YES" attributeType="Integer 64" defaultValueString="0" usesScalarValueType="YES"/>
<attribute name="id" optional="YES" attributeType="Integer 64" defaultValueString="0" usesScalarValueType="YES"/>
<attribute name="markedDeleted" optional="YES" attributeType="Boolean" usesScalarValueType="YES"/>
<attribute name="modificationTime" optional="YES" attributeType="Integer 64" defaultValueString="0" usesScalarValueType="YES"/>
<attribute name="population" optional="YES" attributeType="Integer 64" defaultValueString="0" usesScalarValueType="YES"/>
<attribute name="timezone" optional="YES" attributeType="String"/>
<attribute name="type" optional="YES" attributeType="String"/>
<attribute name="wikipedia" optional="YES" attributeType="String"/>
<relationship name="coordinate" optional="YES" maxCount="1" deletionRule="Cascade" destinationEntity="CDCoordinate" inverseName="location" inverseEntity="CDCoordinate"/>
<relationship name="forecast" optional="YES" maxCount="1" deletionRule="Cascade" destinationEntity="CDWeatherForecast" inverseName="location" inverseEntity="CDWeatherForecast"/>
<relationship name="names" optional="YES" toMany="YES" deletionRule="Cascade" destinationEntity="CDNamesDictionary" inverseName="location" inverseEntity="CDNamesDictionary"/>
</entity>
<entity name="CDNamesDictionary" representedClassName="CDNamesDictionary" syncable="YES">
<attribute name="key" optional="YES" attributeType="String"/>
<attribute name="value" optional="YES" attributeType="String"/>
<relationship name="location" optional="YES" maxCount="1" deletionRule="Nullify" destinationEntity="CDLocation" inverseName="names" inverseEntity="CDLocation"/>
</entity>
<entity name="CDWeatherCondition" representedClassName="CDWeatherCondition" syncable="YES" codeGenerationType="class">
<attribute name="cloudCoverage" optional="YES" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>
<attribute name="cloudDepth" optional="YES" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>
<attribute name="duration" optional="YES" attributeType="Integer 64" defaultValueString="0" usesScalarValueType="YES"/>
<attribute name="hour" optional="YES" attributeType="Integer 64" defaultValueString="0" usesScalarValueType="YES"/>
<attribute name="humidity" optional="YES" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>
<attribute name="precipitation" optional="YES" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>
<attribute name="pressure" optional="YES" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>
<attribute name="snowDepth" optional="YES" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>
<attribute name="source" optional="YES" attributeType="String"/>
<attribute name="temperature" optional="YES" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>
<attribute name="time" optional="YES" attributeType="Integer 64" defaultValueString="0" usesScalarValueType="YES"/>
<attribute name="type" optional="YES" attributeType="String"/>
<attribute name="windDirection" optional="YES" attributeType="String"/>
<attribute name="windSpeed" optional="YES" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>
<relationship name="forecast" optional="YES" maxCount="1" deletionRule="Nullify" destinationEntity="CDWeatherForecast" inverseName="conditions" inverseEntity="CDWeatherForecast"/>
</entity>
<entity name="CDWeatherForecast" representedClassName="CDWeatherForecast" syncable="YES" codeGenerationType="class">
<attribute name="creationTime" optional="YES" attributeType="Integer 64" defaultValueString="0" usesScalarValueType="YES"/>
<attribute name="id" optional="YES" attributeType="Integer 64" defaultValueString="0" usesScalarValueType="YES"/>
<attribute name="markedDeleted" optional="YES" attributeType="Boolean" usesScalarValueType="YES"/>
<attribute name="modificationTime" optional="YES" attributeType="Integer 64" defaultValueString="0" usesScalarValueType="YES"/>
<attribute name="plantCoverage" optional="YES" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>
<attribute name="soilType" optional="YES" attributeType="String"/>
<attribute name="source" optional="YES" attributeType="String"/>
<attribute name="surfaceHeight" optional="YES" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>
<relationship name="conditions" optional="YES" toMany="YES" deletionRule="Cascade" destinationEntity="CDWeatherCondition" inverseName="forecast" inverseEntity="CDWeatherCondition"/>
<relationship name="location" optional="YES" maxCount="1" deletionRule="Nullify" destinationEntity="CDLocation" inverseName="forecast" inverseEntity="CDLocation"/>
</entity>
<elements>
<element name="Location" positionX="-63" positionY="-18" width="128" height="73"/>
<element name="CDCoordinate" positionX="-54" positionY="0" width="128" height="88"/>
<element name="CDLocation" positionX="-366.6015625" positionY="20.45703125" width="128" height="223"/>
<element name="CDNamesDictionary" positionX="36" positionY="270" width="128" height="88"/>
<element name="CDWeatherCondition" positionX="-227.6640625" positionY="303.65625" width="128" height="268"/>
<element name="CDWeatherForecast" positionX="440.50390625" positionY="4.93359375" width="128" height="193"/>
</elements>
</model>
+10 -5
View File
@@ -32,14 +32,18 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
UserData.shared.login(onSuccess: { Devices.shared.refresh() },
onError: {})
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
// Create the SwiftUI view that provides the window content
let contentView = ContentView()
.environmentObject(favorites)
.environmentObject(UserData.shared)
.environmentObject(DeviceData.shared)
.environmentObject(Devices.shared)
.environment(\.managedObjectContext, context)
.environmentObject(NewFavoriteLocation.shared)
.environmentObject(UserData.shared)
.environmentObject(DeviceData.shared)
.environmentObject(Devices.shared)
.environmentObject(favorites)
AltimeterService.shared.generate(completion: { })
LocationService.shared.requestUseLocationService()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
@@ -77,6 +81,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
func sceneDidEnterBackground(_ scene: UIScene) {
MeasurementService.shared.scheduleMeasurementBGService()
(UIApplication.shared.delegate as? AppDelegate)?.saveContext()
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
@@ -0,0 +1,104 @@
//
// FavoriteDetail.swift
// app
//
// Created by Tobias Stottrop on 27.01.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
import SwiftUI
struct FavoriteDetail: View {
@EnvironmentObject var favorites: NewFavoriteLocation
var location: CDLocation?
private func getCurrentCDWeatherCondition() -> some View {
guard ((location?.forecast?.conditions) != nil)
else {
return FavoriteHeaderView()
}
for case let item as CDWeatherCondition in (location?.forecast!.conditions)! {
let epochInMS = Date().timeIntervalSince1970 * 1000;
let withGMT = epochInMS + (self.location?.getMillisecondsFromGMT() ?? 0 )
if (Int64(withGMT) > item.time && Int64(withGMT) <= ((item.time + Int64(item.duration * 3600 * 1000)))) {
return FavoriteHeaderView(condition: item)
}
}
return FavoriteHeaderView()
}
func getTodayView() -> some View {
return FavoriteTodayView(location: location)
}
func getNextDaysView() -> some View {
return FavoritesNextDaysView(location: location)
}
var body: some View {
ScrollView {
VStack(alignment: .leading) {
Text("Now")
.font(.headline)
.padding(10)
Card {
self.getCurrentCDWeatherCondition()
}.padding(10)
}
VStack(alignment: .leading) {
Text("Today")
.font(.headline)
.padding(10)
Card {
self.getTodayView()
}.padding(10)
}
VStack(alignment: .leading) {
Text("Next Days")
.font(.headline)
.padding(10)
Card {
self.getNextDaysView()
}.padding(10)
}
}
.navigationBarTitle(location?.getName() ?? "N/A")
.navigationBarItems(trailing:
VStack {
Button(action: {
if (self.location != nil) {
self.favorites.toggleLocation(self.location!)
}
}) {
Image(systemName: (self.favorites.savedFavorites.first(where: {$0.id == location?.id}) != nil) ? "heart.fill" : "heart")
.foregroundColor(Color.red)
.font(Font.system(size: 25))
}
})
.onAppear(perform: self.fetch)
}
private func fetch() {
if (location != nil) {
favorites.update(location!)
}
}
}
struct FavoriteDetail_Previews: PreviewProvider {
static var previews: some View {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let stub = CDLocation(context: context)
return FavoriteDetail(location: stub).environmentObject(NewFavoriteLocation.shared)
}
}
@@ -0,0 +1,50 @@
//
// FavoriteHeaderView.swift
// app
//
// Created by Tobias Stottrop on 27.01.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
import SwiftUI
struct FavoriteHeaderView: View {
var condition: CDWeatherCondition?
func getDateAsString() -> String {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "de_DE")
formatter.dateStyle = .medium
formatter.timeStyle = .short
if (condition != nil) {
let unixTime = Double(condition!.time)/1000
let date = Date(timeIntervalSince1970: unixTime)
return formatter.string(from: date)
}
return formatter.string(from: Date())
}
var body: some View {
VStack(alignment: .leading) {
Text(getDateAsString())
HStack {
Spacer()
HStack(alignment: .center, spacing: 16) {
Image(systemName: condition?.type ?? "questionmark")
.font(.largeTitle)
Text("\(String(Int(condition?.temperature ?? 0)))°")
.font(.largeTitle)
}
Spacer()
}
HStack {
Image(systemName: "wind")
Image(systemName: condition?.windDirection ?? "questionmark")
Spacer()
Text("\(condition?.windSpeed ?? 0) km/h")
}
}
}
}
+26 -9
View File
@@ -11,24 +11,37 @@ import MowestaApi
struct FavoriteList: View {
@EnvironmentObject var favorites: FavoriteLocations
@EnvironmentObject var newFavoriteLocation: NewFavoriteLocation
@FetchRequest(
entity: CDLocation.entity(),
sortDescriptors: []
) var allLocations: FetchedResults<CDLocation>
@UIState private var searchFavorites = false;
private func deleteItem(at indexSet: IndexSet) {
self.favorites.locations.remove(atOffsets: indexSet)
}
private func setFavoriteListItemView (for location: SavedMowestaFavorites) -> some View {
let loc = allLocations.first(where: {
$0.id == location.id
})
return NavigationLink(destination: FavoriteDetail(location: loc)) {FavoriteListItemView(cdLocation: loc)}
}
var body: some View {
NavigationView {
List{
ForEach(favorites.locations, id: \._id) { location in
NavigationLink(destination: LocationDetail(location: location)) {
FavoriteRow(location: location)
}
}
.onDelete(perform: self.deleteItem)
.onMove { (indexSet, index) in
self.favorites.locations.move(fromOffsets: indexSet, toOffset: index)
List {
ForEach(newFavoriteLocation.savedFavorites) { location in
self.setFavoriteListItemView(for: location)
}
.onDelete(perform: self.newFavoriteLocation.deleteLocation)
.onMove(perform: self.newFavoriteLocation.move)
}
.listStyle(GroupedListStyle())
.navigationBarTitle("Favorites", displayMode: .automatic)
@@ -38,9 +51,11 @@ struct FavoriteList: View {
}){
Text("Add")
})
}.sheet(isPresented: $searchFavorites) {
FavoriteSearch(isPresented: self.$searchFavorites)
.environmentObject(self.favorites)
.environmentObject(self.newFavoriteLocation)
}
}
}
@@ -49,5 +64,7 @@ struct FavoriteList_Previews: PreviewProvider {
static var previews: some View {
FavoriteList()
.environmentObject(FavoriteLocations(locations: [locationEssen]))
.environmentObject(NewFavoriteLocation.shared)
}
}
@@ -0,0 +1,66 @@
//
// FavoriteListItemView.swift
// app
//
// Created by Tobias Stottrop on 24.01.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
import SwiftUI
import CoreData
struct FavoriteListItemView: View {
var cdLocation: CDLocation?
let currentDate: Date = Date()
func getCurrentValues() -> some View {
let content = HStack{
Image(systemName: "sun.min")
Text("0")
}
guard ((cdLocation?.forecast?.conditions) != nil)
else {
return content
}
for case let item as CDWeatherCondition in (cdLocation?.forecast!.conditions)! {
let epochInMS = self.currentDate.timeIntervalSince1970 * 1000;
let withGMT = epochInMS + (self.cdLocation?.getMillisecondsFromGMT() ?? 0 )
if (Int64(withGMT) > item.time && Int64(withGMT) <= ((item.time + Int64(item.duration * 3600 * 1000)))) {
return HStack {
Image(systemName: item.type!)
Text("\(Int(item.temperature))°")
}
}
}
/*let startForecast = Date(timeIntervalSince1970: Double(item.time))
let durationInMs = item.duration * 3600 * 1000
let endForecast = Date(timeIntervalSince1970: Double(item.time + durationInMs))
if (startForecast > currentDate && endForecast < currentDate) {
return HStack {
Image(systemName: item.type!)
Text("\(item.temperature)")
}
}
}*/
return content;
}
var body: some View {
HStack {
Text(cdLocation?.getName() ?? "N/A")
Spacer()
getCurrentValues()
}
}
}
@@ -0,0 +1,29 @@
//
// FavoriteNextDaysDayView.swift
// app
//
// Created by Tobias Stottrop on 27.01.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
import SwiftUI
struct FavoriteNextDaysDayView: View {
var date: String
var temp: String
var type: String
var body: some View {
HStack {
Text(date)
Spacer()
Image(systemName: type)
Text(temp)
}
}
}
struct FavoriteNextDaysDayView_Previews: PreviewProvider {
static var previews: some View {
FavoriteNextDaysDayView(date: "Montag,12:44 Uhr", temp: "22", type:"sun")
}
}
@@ -13,6 +13,7 @@ struct FavoriteSearchResultRow: View {
var location: LocationHierarchy
@EnvironmentObject var favorites: FavoriteLocations
@EnvironmentObject var newFavoriteLocation: NewFavoriteLocation
@UIState private var reload = false
var delimeter: String {
@@ -89,12 +90,11 @@ struct FavoriteSearchResultRow: View {
}
Button(action: {
self.newFavoriteLocation.toggleLocation(self.location)
self.favorites.toggleLocation(self.location)
self.reload = !self.reload
}) {
Image(systemName: favorites.locations.contains{ element in
return element == location
} ? "heart.fill" : "heart").foregroundColor(Color.red)
Image(systemName: (newFavoriteLocation.savedFavorites.firstIndex(where: {$0.id == location._id}) != nil) ? "heart.fill" : "heart").foregroundColor(Color.red)
.font(Font.system(size: 25))
}
@@ -0,0 +1,41 @@
//
// FavoriteTodayView.swift
// app
//
// Created by Tobias Stottrop on 27.01.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
import SwiftUI
struct FavoriteTodayView: View {
var location: CDLocation?
func getSortedConditions() -> [CDWeatherCondition] {
guard ((location?.forecast?.conditions) != nil)
else {
return []
}
var content = (location?.forecast?.conditions as! Set<CDWeatherCondition>).sorted(by: { $0.hour < $1.hour })
content.removeAll(where: {$0.hour > 24})
return content
}
var body: some View {
ScrollView(.horizontal){
HStack(spacing: 8) {
ForEach(getSortedConditions(), id: \.hour) { cond in
VStack(spacing: 8) {
Text("\(cond.hour) Uhr")
.font(.footnote)
Image(systemName: cond.type ?? "questionmark")
.font(.body)
Text("\(String(Int(cond.temperature )))°")
.font(.headline)
}.frame(width: 40)
}
}
}
}
}
@@ -0,0 +1,74 @@
//
// FavoritesNextDaysView.swift
// app
//
// Created by Tobias Stottrop on 27.01.20.
// Copyright © 2020 Marcus Handte. All rights reserved.
//
import SwiftUI
struct FavoritesNextDaysView: View {
var location: CDLocation?
func getDay(value: Int) -> String {
switch value {
case 1:
return "Sunday"
case 2:
return "Monday"
case 3:
return "Tuesday"
case 4:
return "Wednesday"
case 5:
return "Thursday"
case 6:
return "Friday"
case 7:
return "Saturday"
default:
return ""
}
}
func groupedEpisodesByDay(_ episodes: [CDWeatherCondition]) -> [Date: [CDWeatherCondition]] {
let empty: [Date: [CDWeatherCondition]] = [:]
return episodes.reduce(into: empty) { acc, cur in
let unixTime = Double(cur.time)/1000
let fromdate = Date(timeIntervalSince1970: unixTime)
let components = Calendar.current.dateComponents([.day], from: fromdate)
let date = Calendar.current.date(from: components)!
let existing = acc[date] ?? []
acc[date] = existing + [cur]
}
}
func getDayOfWeek(_ today: Int64) -> String {
let unixTime = Double(today)/1000
let date = Date(timeIntervalSince1970: unixTime)
let dateFormatter = DateFormatter()
//dateFormatter.dateFormat = "EEEE"
dateFormatter.locale = Locale(identifier: "de_DE")
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .short
return dateFormatter.string(from: date)
}
func getDays() -> [CDWeatherCondition] {
guard ((location?.forecast?.conditions) != nil)
else {
return []
}
return (location?.forecast?.conditions as! Set<CDWeatherCondition>).sorted(by: { $0.time < $1.time })
//print("\(groupedEpisodesByDay(content))"
}
var body: some View {
VStack {
ForEach(self.getDays(), id: \.self) {item in
FavoriteNextDaysDayView(date: self.getDayOfWeek(item.time), temp: "\(Int(item.temperature))°C", type: item.type ?? "questionmark")
}
}
}
}