테링 프로젝트를 진행하면서 테니스 스윙 데이터를 수집하기 위해 별도의 데이터 수집용 앱을 만들었습니다.

해당 앱에서 애플워치 센서 데이터를 수집하고 CSV 파일로 저장하기 위해 공부한 내용입니다.

func saveToCSV() {
    var csvText = "칼럼1,칼럼2,칼럼3\n1,2,3\n4,5,6\n7,8,9"
    
    let fileManager = FileManager.default
    guard let documentsPath = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else {
        print("Failed to access documents directory.")
        return
    }
    
    let fileURL = documentsPath.appendingPathComponent("my_data.csv")
    
    do {
        try csvText.write(to: fileURL, atomically: true, encoding: .utf8)
        print("CSV file saved at: \(fileURL)")
    } catch {
        print("Failed to save CSV file: \(error.localizedDescription)")
    }
}
func saveToCSV() {
    let fileManager = FileManager.default

    let folderName = "생성할폴더이름"
    let csvFileName = "my_data.csv"

    // 폴더 생성
    guard let documentURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else {
        print("Failed to access documents directory.")
        return
    }
    let directoryURL = documentURL.appendingPathComponent(folderName)
    do {
        try fileManager.createDirectory(atPath: directoryURL.path, withIntermediateDirectories: true)
    }
    catch let error as NSError {
        print("폴더 생성 에러!!!: \(error)")
    }

    // CSV 파일 생성
    let fileURL = directoryURL.appendingPathComponent(csvFileName)
    do {
        try csv문자열.write(to: fileURL, atomically: true, encoding: .utf8)
        print("CSV file saved at: \(fileURL)")
    }
    catch let error as NSError {
        print("Failed to save CSV file!!!: \(error.localizedDescription)")
    }
}

저장된 데이터 확인하기