瀏覽代碼

A timer is working

Thomas Chef 3 年之前
父節點
當前提交
d950383e8b

+ 4 - 0
JourneyGPSTracker.xcodeproj/project.pbxproj

@@ -9,6 +9,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 */; };
+		F5C6949A281D20F600A01960 /* RepeatingTimer.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5C69499281D20F600A01960 /* RepeatingTimer.swift */; };
 		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 */; };
@@ -21,6 +22,7 @@
 		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>"; };
+		F5C69499281D20F600A01960 /* RepeatingTimer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RepeatingTimer.swift; 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>"; };
@@ -79,6 +81,7 @@
 				F5F388CE280B231500087E94 /* Info.plist */,
 				F5A69F9E280C0165001B0EBF /* SendPOSTData.swift */,
 				F5B11AB5281C40C1008BFBF6 /* Model.xcdatamodeld */,
+				F5C69499281D20F600A01960 /* RepeatingTimer.swift */,
 			);
 			path = JourneyGPSTracker;
 			sourceTree = "<group>";
@@ -155,6 +158,7 @@
 			buildActionMask = 2147483647;
 			files = (
 				F5F388C5280B231400087E94 /* ViewController.swift in Sources */,
+				F5C6949A281D20F600A01960 /* RepeatingTimer.swift in Sources */,
 				F5F388C1280B231400087E94 /* AppDelegate.swift in Sources */,
 				F5B11AB7281C40C1008BFBF6 /* Model.xcdatamodeld in Sources */,
 				F5F388C3280B231400087E94 /* SceneDelegate.swift in Sources */,

+ 1 - 0
JourneyGPSTracker/Base.lproj/Main.storyboard

@@ -78,6 +78,7 @@
                         <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"/>
+                        <outlet property="trackingActivateSwitch" destination="vwo-8o-W4T" id="pP3-9y-Yxq"/>
                     </connections>
                 </viewController>
                 <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>

+ 45 - 0
JourneyGPSTracker/RepeatingTimer.swift

@@ -0,0 +1,45 @@
+//
+//  RepeatingTimer.swift
+//  JourneyGPSTracker
+//
+//  Created by Thomas Chef on 2022-04-30.
+//  Copyright © 2022 Thomas Chef. All rights reserved.
+//
+
+import Foundation
+
+class RepeatingTimer {
+    let timeInterval: TimeInterval
+    init(timeInterval: TimeInterval) {
+        self.timeInterval = timeInterval
+    }
+    private lazy var timer: DispatchSourceTimer = {
+        let t = DispatchSource.makeTimerSource()
+        t.schedule(deadline: .now() + self.timeInterval, repeating:                             self.timeInterval)
+        t.setEventHandler(handler: { [weak self] in
+            self?.eventHandler?()
+        })
+        return t
+    }()
+    var eventHandler: (() -> Void)?
+    private enum State {
+        case suspended
+        case resumed
+    }
+    private var state: State = .suspended
+    func resume() {
+        if state == .resumed {
+            return
+        }
+        state = .resumed
+        timer.resume()
+    }
+    
+    func suspend() {
+        if state == .suspended {
+            return
+        }
+        state = .suspended
+        timer.suspend()
+    }
+}

+ 56 - 0
JourneyGPSTracker/SendPOSTData.swift

@@ -8,6 +8,8 @@
 
 import Foundation
 import CoreLocation
+import UIKit
+import CoreData
 
 struct Person: Codable {
     var latitude: Double
@@ -15,12 +17,66 @@ struct Person: Codable {
     var test: Int
 }
 
+var t:RepeatingTimer = RepeatingTimer(timeInterval: 10)
+
+//let appDelegate = UIApplication.shared.delegate as! AppDelegate
+//var logData: [NSManagedObject] = []
+
+//let managedContext = appDelegate.persistentContainer.viewContext
+//let entity = NSEntityDescription.entity(forEntityName: "GPS", in: managedContext)!
+
+//let appDelegate: AppDelegate? = UIApplication.shared.delegate as? AppDelegate
+//appDelegate?.application(UIApplication.shared, didFinishLaunchingWithOptions: nil)
+
+func setupBackgroudTask() {
+    t.eventHandler = timerTask
+        //print("Timer Fired")
+    //}
+    
+    
+}
+
+
+func activateBackgroundTask() {
+    t.resume()
+}
+
+func deactivateBackgroundTask() {
+    t.suspend()
+}
+
+func timerTask() {
+    print("Timer Fired")
+    
+/*
+    return
+    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "GPS")
+    print("Timer Fired B")
+    do {
+        print("Timer Fired C")
+        logData = try managedContext.fetch(fetchRequest)
+        print("Timer Fired D")
+        print( "Cnt:" + String(logData.count) )
+        print("Timer Fired E")
+    } catch let error as NSError {
+        print("Could not fetch. \(error), \(error.userInfo)")
+    }
+    print("Timer Fired F")*/
+}
+
+
 //class SendPOSTData {
     
     func placeOrder(didUpdateLocations locations: [CLLocation]) {
+        
+        
+
         print("placeOrder")
         locations.forEach { (location) in
             
+            //let managedContext = appDelegate.persistentContainer.viewContext
+            //let entity = NSEntityDescription.entity(forEntityName: "GPS", in: managedContext)!
+            
             let person = Person(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude, test: 564)
             let jsonEncoder = JSONEncoder()
             jsonEncoder.outputFormatting = .prettyPrinted

+ 31 - 14
JourneyGPSTracker/ViewController.swift

@@ -17,7 +17,8 @@ class ViewController: UIViewController {
     @IBOutlet weak var noOfSentGPSToServer: UILabel!
     @IBOutlet weak var pauseSwitch: UISwitch!
     @IBOutlet weak var clickButton: UIButton!
-
+    @IBOutlet weak var trackingActivateSwitch: UISwitch!
+    
     var locationManager: CLLocationManager?
     
     var noOfSentPos: Int = 0
@@ -39,6 +40,32 @@ class ViewController: UIViewController {
         locationManager?.distanceFilter = 100.0
         locationManager?.allowsBackgroundLocationUpdates = true
         pauseSwitch.isEnabled = false
+        
+    }
+    
+    func setupTimer() {
+        
+        _ = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { timer in
+            
+            print("New Timer fired!")
+            
+            let managedContext = self.appDelegate.persistentContainer.viewContext
+            let entity = NSEntityDescription.entity(forEntityName: "GPS", in: managedContext)!
+            let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "GPS")
+            do {
+                self.gpsLogData = try managedContext.fetch(fetchRequest)
+                print( "Cnt:" + String(self.gpsLogData.count) )
+            } catch let error as NSError {
+                print("Could not fetch. \(error), \(error.userInfo)")
+            }
+            if( self.trackingActivateSwitch.isOn == false ) {
+                timer.invalidate()
+                print("Stopping Timer")
+            }
+        }
+    }
+    
+    @objc func fireTimer() {
     }
     
     @IBAction func tackingPauseChanged(_ sender: UISwitch) {
@@ -58,8 +85,6 @@ class ViewController: UIViewController {
         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 {
@@ -71,6 +96,8 @@ class ViewController: UIViewController {
             locationManager?.startUpdatingLocation()
             pauseSwitch.isEnabled = true
             noOfSentPos = 0
+            //activateBackgroundTask()
+            setupTimer()
         default:
             print("OFF")
             locationManager?.stopUpdatingLocation()
@@ -79,17 +106,7 @@ class ViewController: UIViewController {
         }
     }
     
-    func viewDidBecomeActive(){
-        print("viewDidBecomeActive")
-    }
-    
-    override func viewDidDisappear(_ animated: Bool) {
-        print("viewDidBecomeINActive")
-    }
-    
-
-
-    
+   
 }
 
 extension ViewController: CLLocationManagerDelegate {