테링 프로젝트를 진행하면서 테니스 스윙 데이터를 수집하기 위해 별도의 데이터 수집용 앱을 만들었습니다.
해당 앱에서 애플워치 센서 데이터를 수집하고 CSV 파일로 저장하기 위해 공부한 내용입니다.
FileManager를 사용하여 문서 디렉토리의 경로를 가져온 후, 해당 경로에 .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)")
}
}
저장된 데이터 확인하기
CSV 파일은 앱이 실행되는 기기의 문서 디렉토리에 저장됨. 시뮬레이터를 사용하는 경우, 파일은 시뮬레이터의 디렉토리에 저장되며, 실제 기기를 사용하는 경우 파일은 해당 기기의 파일 시스템에 저장됨
애플 워치는 iOS 기기와 달리 앱 컨테이너에 직접 액세스할 수 있는 파일 시스템을 제공하지 않음
⇒ 따라서 애플워치에서 device motion 데이터 같은걸 수집할 땐 iOS로 전송한 뒤에 CSV파일로 저장해줘야 하는 것 같음
iOS 기기에서 확인하는 방법
Xcode → Window → Devices and Simulators → 연결된 기기 선택 → 해당 앱 선택 → 더보기 아이콘 버튼 → Download Container → 다운로드한 .xcappdata 우클릭 → 패키지 내용 보기 → AppData → 지정한 경로로 가서 파일 확인





