Slide 53
Slide 53 text
XMLParserʹΑΔ
SAXॲཧྫ
class HealthDataParser: NSObject, XMLParserDelegate {
private var bodyMassRecords: [[String: String]] = []
private var isParsingRecord = false
func parseHealthData(contents: URL) -> [[String: String]] {
let parser = XMLParser(contentsOf: contents)
parser?.delegate = self
parser?.parse()
return bodyMassRecords
}
func parser(_ parser: XMLParser,
didStartElement elementName:
String, namespaceURI: String?,
qualifiedName qName: String?,
attributes attributeDict: [String : String] = [:]) {
if elementName == "Record" && attributeDict["type"] == "HKQuantityTypeIdentifierBodyMass" {
isParsingRecord = true
if attributeDict.contains(where: { key, value in
key == "value" && Double(value)! < 70
}) {
bodyMassRecords.append(attributeDict)
if bodyMassRecords.count > 20 { parser.abortParsing() }
}
}
}
func parser(_ parser: XMLParser,
didEndElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?) {
if elementName == "Record" { isParsingRecord = false }
}
}
• XMLParserΛϩʔΧϧϑΝΠϧURLύ
ε(contentsOf:)Ͱੜ
• ඞཁͳऔಘରͷσʔλ(record)ͷॲཧ
Λߦ͏
• औಘ͠ऴΘͬͨΒ
parser.abortParsing()Λݺͼग़ͯ͠
XMLͷಡΈࠐΈΛΩϟϯηϧ͢Δ