Please tell me, I can’t save myDate data to a .txt file, which I haven’t tried. I read the accelerometer readings and then output them to the command line, but I want to save

import UIKit import CoreMotion class ViewController: UIViewController { var motionManager = CMMotionManager() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(_ animated: Bool) { motionManager.accelerometerUpdateInterval = 1 motionManager.startAccelerometerUpdates(to: OperationQueue.current!) { (data, error) in if let myData = data { //if myData.acceleration.x > 1 //{ print (myData) //} } } } 

    1 answer 1

    If you want to save to a file, add:

     let logFilePath = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("LogFile.txt"))! /// Запись в файл если пусто, дозапись, если что-то уже есть func logToFile(data: Data) { guard let fileHandle = FileHandle(forWritingAtPath: logFilePath.path) else { try! data.write(to: logFilePath) return } fileHandle.seekToEndOfFile() fileHandle.write(data) fileHandle.closeFile() } /// Для распечатки сохраненных в файл логов. func printLogFileData() { let result = try! String(contentsOf: logFilePath, encoding: .utf8) print(result) } 

    And instead of print (myData) call:

     self.logToFile(data: "\(myData)\n".description.data(using: String.Encoding.utf8)!)