Search code examples
swiftxmlabort

Parsing XML in swift fails with nil error


I am attempting to parse an xml file using Swift. I have created a XMLParserDelegate class, OSM, which implements the following functions:

func parserDidStartDocument(_ parser: XMLParser)
func parserDidEndDocument(_ parser: XMLParser)
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:])
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)

I use the delegate as follows:

let url = URL(string: "file:///Users/<Username>/Documents/Maps/OSMFiles/simple.osm")!
print(url.absoluteString)
let parser = XMLParser(contentsOf: url)!
let osm = OSM()
parser.delegate = osm
print(parser.parse())
print(parser.parserError)

The code prints the following:

file:///Users/<Username>/Documents/Maps/OSMFiles/simple.osm
false
nil

Solution

  • It turns out the app sandboxing was the issue, possibly because I was trying to access a file outside the sandbox. Turning off sandboxing solves the issue.