瀏覽代碼

Array insert into SQL works to http server

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

+ 1 - 1
JourneyGPSTracker/Model.xcdatamodeld/Model.xcdatamodel/contents

@@ -1,7 +1,7 @@
 <?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="latitude" optional="YES" attributeType="Double" 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>

+ 40 - 97
JourneyGPSTracker/SendPOSTData.swift

@@ -11,112 +11,55 @@ import CoreLocation
 import UIKit
 import CoreData
 
-struct Person: Codable {
+struct GPS_POS_LOG: Codable {
     var latitude: Double
     var longitude: Double
-    var test: Int
+    var ts: String
 }
 
-var t:RepeatingTimer = RepeatingTimer(timeInterval: 10)
+func sendToHttpServer(gpsPosLog: [GPS_POS_LOG]) {
 
-//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")
+    print("sendToHttpServer()")
+        
+    let jsonEncoder = JSONEncoder()
+    jsonEncoder.outputFormatting = .prettyPrinted
+  
+    var uploadData:Data?
     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)")
+        uploadData = try jsonEncoder.encode(gpsPosLog)
+    } catch {
+        print(error.localizedDescription)
+        return
     }
-    print("Timer Fired F")*/
-}
-
-
-//class SendPOSTData {
+    //print( gpsPosLog )
     
-    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
-          
-            var uploadData:Data?
-            do {
-                uploadData = try jsonEncoder.encode(person)
-                //let endcodeStringPerson = String(data: uploadData! , encoding: .utf8)!
-                //print(endcodeStringPerson)
-            } catch {
-                print(error.localizedDescription)
-            }
-            
-            let url = URL(string: "http://chef.maya.se/gpsapi/registerGPSlocation.php")!
-            var request = URLRequest(url: url)
-            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
-            request.httpMethod = "POST"
-            
-            let task = URLSession.shared.uploadTask(with: request, from: uploadData) { data, response, error in
-                if let error = error {
-                    print ("error: \(error)")
-                    return
-                }
-                guard let response = response as? HTTPURLResponse,
-                    (200...299).contains(response.statusCode) else {
-                    print ("server error")
-                    return
-                }
-                if let mimeType = response.mimeType,
-                    mimeType == "text/html",
-                    let data = data,
-                    let dataString = String(data: data, encoding: .utf8) {
-                    print ("got data: \(dataString)")
-                }
-                else {
-                    print("KALLE:" + String(response.mimeType!))
-                }
-            }
-            task.resume()
+    let url = URL(string: "http://chef.maya.se/gpsapi/registerGPSlocation.php")!
+    var request = URLRequest(url: url)
+    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
+    request.httpMethod = "POST"
+    
+    let task = URLSession.shared.uploadTask(with: request, from: uploadData) { data, response, error in
+        if let error = error {
+            print ("error: \(error)")
+            return
+        }
+        guard let response = response as? HTTPURLResponse,
+            (200...299).contains(response.statusCode) else {
+            print ("200-299 server error")
+            return
+        }
+        if let mimeType = response.mimeType,
+            mimeType == "text/html",
+            let data = data,
+            let dataString = String(data: data, encoding: .utf8) {
+            print ("got data: \(dataString)")
+        }
+        else {
+            print("KALLE:" + String(response.mimeType!))
         }
     }
+    task.resume()
+
+}
 
 //}

+ 29 - 15
JourneyGPSTracker/ViewController.swift

@@ -43,18 +43,39 @@ class ViewController: UIViewController {
         
     }
     
+    func convertStartDate(StartDate: Date) -> String {
+
+        let dateFormatter = DateFormatter()
+        dateFormatter.timeZone = TimeZone.current
+        dateFormatter.dateFormat = "yyy-MM-dd' 'HH:mm:ss"
+        let dateString = dateFormatter.string(from: StartDate)
+        //dateFormatter.dateFormat = "yyy-MM-dd HH:mm:ss +0000"
+        //let date = dateFormatter.date(from: dateString)
+        return dateString
+    }
+    
     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")
+            let cnxt = self.appDelegate.persistentContainer.viewContext
+            let request: NSFetchRequest<GPS> = GPS.fetchRequest()
+            
             do {
-                self.gpsLogData = try managedContext.fetch(fetchRequest)
-                print( "Cnt:" + String(self.gpsLogData.count) )
+                let fd = try cnxt.fetch(request)
+                print( "Cnt:" + String(fd.count) )
+                
+                var positions: [GPS_POS_LOG] = []
+                
+                fd.forEach { row in
+                    let ts = self.convertStartDate(StartDate: row.ts!)
+                    let gpsPosLog = GPS_POS_LOG(latitude:row.latitude,longitude: row.longitud,ts: ts)
+                    positions.append(gpsPosLog)
+                }
+                sendToHttpServer(gpsPosLog: positions)
+                
             } catch let error as NSError {
                 print("Could not fetch. \(error), \(error.userInfo)")
             }
@@ -65,6 +86,8 @@ class ViewController: UIViewController {
         }
     }
     
+
+    
     @objc func fireTimer() {
     }
     
@@ -96,7 +119,6 @@ class ViewController: UIViewController {
             locationManager?.startUpdatingLocation()
             pauseSwitch.isEnabled = true
             noOfSentPos = 0
-            //activateBackgroundTask()
             setupTimer()
         default:
             print("OFF")
@@ -143,7 +165,7 @@ extension ViewController: CLLocationManagerDelegate {
         let managedContext = appDelegate.persistentContainer.viewContext
         let entity = NSEntityDescription.entity(forEntityName: "GPS", in: managedContext)!
 
-      
+        // Loop through all GPS Positions and send them to the Database
         locations.forEach { (location) in
             //print("LocationManager didUpdateLocations: \(dateFormatter.string(from: location.timestamp)); \(location.coordinate.latitude), \(location.coordinate.longitude)")
             print("LocationManager horizontalAccuracy: \(location.horizontalAccuracy)")
@@ -160,14 +182,6 @@ extension ViewController: CLLocationManagerDelegate {
                 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) {