0

I am trying to get device motion as well as raw accelerometer data, saving into csv file. as i try to add second array to csv file it doesnt add with the rest of the columns. I tried this solutions How do I concatenate or merge arrays in Swift? but this doesnt work

enter image description here

i want my csv file to be like this enter image description here

Code for enabling motion updates:

 func enableMotionUpdates() {


    motionManager.deviceMotionUpdateInterval = 1.0 / defHz
    motionManager.accelerometerUpdateInterval = 1.0/defHz


    activityData = [String]()//storing device motion data 
    activityDataAccelro = [String]()//storing accelerometer data

    if motionManager.isAccelerometerAvailable {
        motionManager.startAccelerometerUpdates(
            to: .main,
            withHandler: { [weak self] accelrometerData, error in
            guard let self = self, let accelrometerData = accelrometerData else {
              if let error = error {
                // Just display error for local testing.
                // A more robust solution would include better error logging and
                // stop the session if too many errors occur.
                print("Device motion update error: \(error.localizedDescription)")
              }
              return
            }
                print("in accelro")
          self.processAccelroData(accelrometerData)
        })
    }
    else{
        print("accelro isnot available")
    }

     motionManager.startDeviceMotionUpdates(
       using: .xArbitraryZVertical,
       to: queue, withHandler: { [weak self] motionData, error in
         guard let self = self, let motionData = motionData else {
           if let error = error {
             print("Device motion update error: \(error.localizedDescription)")
           }
           return
         }

        self.processMotionData(motionData)
     })

     self.activityData.append(self.LABLES)
    self.activityDataAccelro.append(self.AccelroLable)
   }

code for storing motion updates into string array

func processMotionData(_ motionData: CMDeviceMotion) {

    numActionsRecorded+=1

    let sample = """

    \( motionData.timestamp),\
     \(motionData.attitude.roll),\
     \(motionData.attitude.pitch),\
     \(motionData.attitude.yaw),\
     \(motionData.rotationRate.x),\
     \(motionData.rotationRate.y),\
     \(motionData.rotationRate.z),\
     \(motionData.gravity.x),\
     \(motionData.gravity.y),\
     \(motionData.gravity.z),\
     \(motionData.userAcceleration.x),\
     \(motionData.userAcceleration.y),\
     \(motionData.userAcceleration.z),\
     \(motionData.attitude.quaternion.x),\
     \(motionData.attitude.quaternion.y),\
     \(motionData.attitude.quaternion.w),\
    \(motionData.attitude.quaternion.z)
    """

     activityData.append(sample)

   }

func processAccelroData(_ accelroData: CMAccelerometerData) {
    let sample = """
    \(accelroData.acceleration.x),\
    \(accelroData.acceleration.y),\
    \(accelroData.acceleration.z)
     """
    activityDataAccelro.append(sample)
    }

Saving data into csv file

 func saveActivityData() {
    var userActivityData = [String]()
  userActivityData = activityData + activityDataAccelro //merging two arrays

    let confirmDialog = WKAlertAction.init(title: "Save",
                                            style: WKAlertActionStyle.default,
                                            handler: { () -> Void in
                                            let dataURL =
                                            getDocumentsDirectory()
                                                .appendingPathComponent("sensorData")
                                                .appendingPathExtension("csv")
                                            do {

                                                try  
                                                userActivityData.appendLinesToURL(fileURL: dataURL)

                                            print("Appended to file \(dataURL.path)")
                                            } catch {
                                            print("Error writing file to \(dataURL): \(error.localizedDescription)")
                                            }

    })


    }
Muhammad Ahmed
  • 131
  • 1
  • 1
  • 7

1 Answers1

1

If your arrays are of equal length you can use zip and map

var arr1 = ["A", "B", "C"]
var arr2 = ["a", "b", "c"]

let combo = Array(zip(arr1, arr2)).map{ "\($0.0),\($0.1)"}

If your arrays are not of equal length then determine which one is shorter and loop over it

var arr1 = ["A", "B", "C", "D"]
var arr2 = ["a", "b", "c"]

for (index, item) in arr2.enumerated() {
    arr1[index] = "\(arr1[index]),\(item)" //If arr2 should be first then simply switch the order
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52