Skip to content

Instantly share code, notes, and snippets.

@manishkkatoch
Last active December 6, 2017 17:19
Show Gist options
  • Save manishkkatoch/c9d64ceae407dd5b6215c44ecda7c167 to your computer and use it in GitHub Desktop.
Save manishkkatoch/c9d64ceae407dd5b6215c44ecda7c167 to your computer and use it in GitHub Desktop.
Parser for .gpx file. communicates using GpxParsing protocol. The caller must implement this protocol to get notified of parse completion. Please use Queue implementation of your choice or see https://gist.github.com/manishkkatoch/0028a637cfc6dc3207d82c104299e08d.
//
// GpxParser.swift
// mockLocation
//
// Created by Manish Katoch on 11/29/17.
// Copyright © 2017 Manish Katoch. All rights reserved.
//
protocol GpxParsing: NSObjectProtocol {
func parser(_ parser: GpxParser, didCompleteParsing locations: Queue<CLLocation>)
}
class GpxParser: NSObject, XMLParserDelegate {
private var locations: Queue<CLLocation>
weak var delegate: GpxParsing?
private var parser: XMLParser?
init(forResource file: String, ofType typeName: String) {
self.locations = Queue<CLLocation>()
super.init()
if let content = try? String(contentsOfFile: Bundle.main.path(forResource: file, ofType: typeName)!) {
let data = content.data(using: .utf8)
parser = XMLParser.init(data: data!)
parser?.delegate = self
}
}
func parse() {
self.parser?.parse()
}
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
switch elementName {
case "trkpt":
if let latString = attributeDict["lat"],
let lat = Double.init(latString),
let lonString = attributeDict["lon"],
let lon = Double.init(lonString) {
locations.enqueue(CLLocation(latitude: lat, longitude: lon))
}
default: break
}
}
func parserDidEndDocument(_ parser: XMLParser) {
delegate?.parser(self, didCompleteParsing: locations)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment