Browse Source

Core Data maybe working a bit

Thomas Chef 3 years ago
parent
commit
e35ebe0c8a

+ 27 - 0
JourneyGPSTracker.xcodeproj/project.pbxproj

@@ -8,6 +8,7 @@
 
 /* Begin PBXBuildFile section */
 		F5A69F9F280C0165001B0EBF /* SendPOSTData.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5A69F9E280C0165001B0EBF /* SendPOSTData.swift */; };
+		F5B11AB7281C40C1008BFBF6 /* Model.xcdatamodeld in Sources */ = {isa = PBXBuildFile; fileRef = F5B11AB5281C40C1008BFBF6 /* Model.xcdatamodeld */; };
 		F5F388C1280B231400087E94 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5F388C0280B231400087E94 /* AppDelegate.swift */; };
 		F5F388C3280B231400087E94 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5F388C2280B231400087E94 /* SceneDelegate.swift */; };
 		F5F388C5280B231400087E94 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5F388C4280B231400087E94 /* ViewController.swift */; };
@@ -18,6 +19,8 @@
 
 /* Begin PBXFileReference section */
 		F5A69F9E280C0165001B0EBF /* SendPOSTData.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SendPOSTData.swift; sourceTree = "<group>"; };
+		F5B11AB3281C4071008BFBF6 /* CoreData.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreData.framework; path = System/Library/Frameworks/CoreData.framework; sourceTree = SDKROOT; };
+		F5B11AB6281C40C1008BFBF6 /* Model.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = Model.xcdatamodel; sourceTree = "<group>"; };
 		F5F388BD280B231400087E94 /* JourneyGPSTracker.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = JourneyGPSTracker.app; sourceTree = BUILT_PRODUCTS_DIR; };
 		F5F388C0280B231400087E94 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
 		F5F388C2280B231400087E94 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = "<group>"; };
@@ -39,11 +42,20 @@
 /* End PBXFrameworksBuildPhase section */
 
 /* Begin PBXGroup section */
+		F5B11AB2281C4071008BFBF6 /* Frameworks */ = {
+			isa = PBXGroup;
+			children = (
+				F5B11AB3281C4071008BFBF6 /* CoreData.framework */,
+			);
+			name = Frameworks;
+			sourceTree = "<group>";
+		};
 		F5F388B4280B231400087E94 = {
 			isa = PBXGroup;
 			children = (
 				F5F388BF280B231400087E94 /* JourneyGPSTracker */,
 				F5F388BE280B231400087E94 /* Products */,
+				F5B11AB2281C4071008BFBF6 /* Frameworks */,
 			);
 			sourceTree = "<group>";
 		};
@@ -66,6 +78,7 @@
 				F5F388CB280B231500087E94 /* LaunchScreen.storyboard */,
 				F5F388CE280B231500087E94 /* Info.plist */,
 				F5A69F9E280C0165001B0EBF /* SendPOSTData.swift */,
+				F5B11AB5281C40C1008BFBF6 /* Model.xcdatamodeld */,
 			);
 			path = JourneyGPSTracker;
 			sourceTree = "<group>";
@@ -143,6 +156,7 @@
 			files = (
 				F5F388C5280B231400087E94 /* ViewController.swift in Sources */,
 				F5F388C1280B231400087E94 /* AppDelegate.swift in Sources */,
+				F5B11AB7281C40C1008BFBF6 /* Model.xcdatamodeld in Sources */,
 				F5F388C3280B231400087E94 /* SceneDelegate.swift in Sources */,
 				F5A69F9F280C0165001B0EBF /* SendPOSTData.swift in Sources */,
 			);
@@ -344,6 +358,19 @@
 			defaultConfigurationName = Release;
 		};
 /* End XCConfigurationList section */
+
+/* Begin XCVersionGroup section */
+		F5B11AB5281C40C1008BFBF6 /* Model.xcdatamodeld */ = {
+			isa = XCVersionGroup;
+			children = (
+				F5B11AB6281C40C1008BFBF6 /* Model.xcdatamodel */,
+			);
+			currentVersion = F5B11AB6281C40C1008BFBF6 /* Model.xcdatamodel */;
+			path = Model.xcdatamodeld;
+			sourceTree = "<group>";
+			versionGroupType = wrapper.xcdatamodel;
+		};
+/* End XCVersionGroup section */
 	};
 	rootObject = F5F388B5280B231400087E94 /* Project object */;
 }

+ 44 - 0
JourneyGPSTracker/AppDelegate.swift

@@ -7,6 +7,7 @@
 //
 
 import UIKit
+import CoreData
 
 @UIApplicationMain
 class AppDelegate: UIResponder, UIApplicationDelegate {
@@ -31,6 +32,49 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
         // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
         // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
     }
+    
+    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: "Model")
+            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 - 11
JourneyGPSTracker/Base.lproj/Main.storyboard

@@ -22,16 +22,6 @@
                                 <fontDescription key="fontDescription" type="system" pointSize="14"/>
                                 <nil key="highlightedColor"/>
                             </label>
-                            <button opaque="NO" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="ibO-RI-Xe4">
-                                <rect key="frame" x="78" y="433" width="241" height="30"/>
-                                <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
-                                <fontDescription key="fontDescription" type="system" pointSize="43"/>
-                                <state key="normal" title="Button"/>
-                                <connections>
-                                    <action selector="buttonClicked:" destination="BYZ-38-t0r" eventType="touchUpInside" id="8fd-cf-kG6"/>
-                                    <action selector="jhfgjf:" destination="BYZ-38-t0r" eventType="editingChanged" id="607-lr-uNy"/>
-                                </connections>
-                            </button>
                             <switch opaque="NO" contentMode="scaleToFill" horizontalHuggingPriority="750" verticalHuggingPriority="750" fixedFrame="YES" contentHorizontalAlignment="center" contentVerticalAlignment="center" title="Tracking on" translatesAutoresizingMaskIntoConstraints="NO" id="vwo-8o-W4T">
                                 <rect key="frame" x="217" y="81" width="49" height="31"/>
                                 <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
@@ -85,7 +75,6 @@
                         <color key="backgroundColor" systemColor="systemBackgroundColor"/>
                     </view>
                     <connections>
-                        <outlet property="clickButton" destination="ibO-RI-Xe4" id="qFc-vE-7Yy"/>
                         <outlet property="noOfRxGPSPos" destination="gjP-2D-NvA" id="7hy-Mg-Vvj"/>
                         <outlet property="noOfSentGPSToServer" destination="yVZ-Xq-Fgc" id="LkD-uQ-QI7"/>
                         <outlet property="pauseSwitch" destination="1zW-3R-nTk" id="z9y-HB-zSj"/>

+ 11 - 0
JourneyGPSTracker/Model.xcdatamodeld/Model.xcdatamodel/contents

@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="20086" systemVersion="21E258" minimumToolsVersion="Automatic" sourceLanguage="Swift" userDefinedModelVersionIdentifier="">
+    <entity name="GPS" representedClassName="GPS" syncable="YES" codeGenerationType="class">
+        <attribute name="latitude" optional="YES" attributeType="Float" defaultValueString="0.0" usesScalarValueType="YES"/>
+        <attribute name="longitud" optional="YES" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>
+        <attribute name="ts" optional="YES" attributeType="Date" usesScalarValueType="NO"/>
+    </entity>
+    <elements>
+        <element name="GPS" positionX="-63" positionY="-18" width="128" height="74"/>
+    </elements>
+</model>

+ 50 - 18
JourneyGPSTracker/ViewController.swift

@@ -8,6 +8,7 @@
 
 import UIKit
 import CoreLocation
+import CoreData
 
 class ViewController: UIViewController {
     
@@ -21,11 +22,14 @@ class ViewController: UIViewController {
     
     var noOfSentPos: Int = 0
     
+    var gpsLogData: [NSManagedObject] = []
+    
+    let appDelegate = UIApplication.shared.delegate as! AppDelegate
+    
     
 
     override func viewDidLoad() {
         super.viewDidLoad()
-        clickButton.isHidden = false
         locationManager = CLLocationManager()
         locationManager?.delegate = self
         locationManager?.requestWhenInUseAuthorization()
@@ -35,14 +39,6 @@ class ViewController: UIViewController {
         locationManager?.distanceFilter = 100.0
         locationManager?.allowsBackgroundLocationUpdates = true
         pauseSwitch.isEnabled = false
-        
-        //noOfReceivedGPSPos.text = "KALLE"
-    }
-    
-    @IBAction func buttonClicked(_ sender: Any) {
-        print("Clicked !")
-        //locationManager?.requestLocation()
-        
     }
     
     @IBAction func tackingPauseChanged(_ sender: UISwitch) {
@@ -50,8 +46,10 @@ class ViewController: UIViewController {
         switch sender.isOn {
         case true:
             print("Pause ON")
+            locationManager?.stopUpdatingLocation()
         default:
             print("Pause OFF")
+            locationManager?.startUpdatingLocation()
         }
     }
     
@@ -59,9 +57,20 @@ class ViewController: UIViewController {
         print("Switch Changed !")
         switch sender.isOn {
         case true:
+            let managedContext = appDelegate.persistentContainer.viewContext
+            //let entity = NSEntityDescription.entity(forEntityName: "GPS", in: managedContext)!
+            //let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "GPS")
+            let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "GPS")
+            let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
+            do {
+                try managedContext.execute(batchDeleteRequest)
+            } catch {
+                // Error Handling
+            }
             print("ON")
             locationManager?.startUpdatingLocation()
             pauseSwitch.isEnabled = true
+            noOfSentPos = 0
         default:
             print("OFF")
             locationManager?.stopUpdatingLocation()
@@ -104,21 +113,44 @@ extension ViewController: CLLocationManagerDelegate {
     
     // Step 7: Handle the location information
     func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
-      print("LocationManager didUpdateLocations: numberOfLocation: \(locations.count)")
-      let dateFormatter = DateFormatter()
-      dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
         
+        print("LocationManager didUpdateLocations: numberOfLocation: \(locations.count)")
+        let dateFormatter = DateFormatter()
+        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
         
         noOfSentPos += 1
         noOfRxGPSPos.text = String(noOfSentPos)
         
-        placeOrder(didUpdateLocations: locations)
+        //placeOrder(didUpdateLocations: locations)
+        
+        let managedContext = appDelegate.persistentContainer.viewContext
+        let entity = NSEntityDescription.entity(forEntityName: "GPS", in: managedContext)!
+
       
-      locations.forEach { (location) in
-        print("LocationManager didUpdateLocations: \(dateFormatter.string(from: location.timestamp)); \(location.coordinate.latitude), \(location.coordinate.longitude)")
-        print("LocationManager horizontalAccuracy: \(location.horizontalAccuracy)")
-        print("LocationManager verticalAccuracy: \(location.verticalAccuracy)")
-      }
+        locations.forEach { (location) in
+            //print("LocationManager didUpdateLocations: \(dateFormatter.string(from: location.timestamp)); \(location.coordinate.latitude), \(location.coordinate.longitude)")
+            print("LocationManager horizontalAccuracy: \(location.horizontalAccuracy)")
+            //print("LocationManager verticalAccuracy: \(location.verticalAccuracy)")
+            
+            let pos = NSManagedObject(entity: entity,insertInto: managedContext)
+            pos.setValue(location.coordinate.longitude, forKey: "longitud")
+            pos.setValue(location.coordinate.latitude, forKey: "latitude")
+            pos.setValue(location.timestamp, forKey: "ts")
+            do {
+                try managedContext.save()
+                //people.append(person)
+            } catch let error as NSError {
+                print("Could not save. \(error), \(error.userInfo)")
+            }
+        }
+        
+        let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "GPS")
+        do {
+            gpsLogData = try managedContext.fetch(fetchRequest)
+            print( "Cnt:" + String(gpsLogData.count) )
+          } catch let error as NSError {
+            print("Could not fetch. \(error), \(error.userInfo)")
+          }
     }
     
     func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {