1. 添加访问文件夹权限
添加以下两条,并把值设置为YES
- UIFileSharingEnabled (Application supports iTunes file sharing)
- LSSupportsOpeningDocumentsInPlace (Supports opening documents in place)
2. 生成CSV文件
func createCSV(from recArray:Dictionary<String, String>) {
var csvString = "\("Type"),\("Number")\n\n"
for dct in recArray {
csvString = csvString.appending("\(String(describing: dct.key)) ,\(String(describing: dct.value))\n")
}
let dateFormat = DateFormatter()
dateFormat.dateFormat = "yyyyMMddHHmmss"
let now = Date()
print(dateFormat.string(from: now))
let fileManager = FileManager.default
do {
let path = try fileManager.url(for: .documentDirectory, in: .allDomainsMask, appropriateFor: nil, create: false)
let fileURL = path.appendingPathComponent("\(dateFormat.string(from: now))_HealthData.csv")
try csvString.write(to: fileURL, atomically: true, encoding: .utf8)
} catch {
print("error creating file")
}
}
3.BLE相关
3.1 中心设备接收消息时的处理
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
print("BLE updated characteristis: \(characteristic)")
// 获取到的值
let data = characteristic.value!
print("data:",data)
// 把json类型转换成字典类型
let json = try! JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String, String>
print("json:",json)
// 屏幕上显示的消息
notifiedMessage = "\(json)"
}
4. 获取时间
func getTime () {
let calendar = Calendar(identifier: .gregorian)
let dateformatter = DateFormatter()
dateformatter.locale = Locale(identifier: "ja_JP")
dateformatter.timeZone = TimeZone(identifier: "Asia/Tokyo")
dateformatter.dateFormat = "yyyy/MM/dd HH:mm:ss"
let now = Date()
// 一天的开始
let withStart = calendar.startOfDay(for: now)
print("withStart:",dateformatter.string(from: withStart))
print("now:",dateformatter.string(from: now))
}
5. HealthKit HKSampleQuery
func addSampleQuery (sampleType: HKQuantityType, predicate: NSPredicate?) {
// ヘルスケアデータを取得
let sampleQuery = HKSampleQuery(sampleType: sampleType,
predicate: predicate,
limit: HKObjectQueryNoLimit,
sortDescriptors: [NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: true)]) { (query, results, error) in
// エラー処理
guard error == nil else {
print("error:\(String(describing: error))")
return
}
// エラー処理
guard let sampleQueryResults = results as? [HKQuantitySample] else {
print("sampleQuery results error")
return
}
print("sampleQueryResults:\(sampleQueryResults)")
var unit: HKUnit?
self.healthStore.preferredUnits(for: [sampleType]) { (preferredType, error) in
guard error == nil else {
print("preferredUnits error:\(String(describing: error))")
return
}
unit = preferredType.first?.value
print("unit:\(String(describing: unit!))")
// 取得したデータを1件ずつ ListRowItem 構造体に格納
// ListRowItemは、dataSource配列に追加します。ViewのListでは、この dataSource配列を参照して心拍数を表示します。
for item in sampleQueryResults {
let listItem = HealthDataTypeValue(
id: item.uuid.uuidString,
startDate: self.dataFormatted(date: item.startDate),
endDate: self.dataFormatted(date: item.endDate),
sampleType: item.sampleType,
value: String(item.quantity.doubleValue(for: unit!))
)
self.dataSource.append(listItem)
print("listItem:\(listItem)")
}
}
}
self.healthStore.execute(sampleQuery)
}