iosswiftnsxmlparsernsxmlparserdelegate

Swift NSXMLParserDelegate doesn't get called


I have a weird problem. The weirdness comes from the fact that the code executes just perfect in playground but it doesn't in simulator...
Long story short, I have a class which should parse a document which I lazy instantiate and invoke the parsing method from a VC. The parsing function gets called in the class but not the delegate functions (parsing started, chars found etc.). This is kinda maddening, as the same setup works just fine in the playground...

Parsing class (and protocol):

protocol DefintionFetching {
    func fetchingDidFinish(results: [String: NSMutableAttributedString])
}

class DefinitionFetcher: NSObject, NSXMLParserDelegate {
    var delegate: DefintionFetching

    var parser = NSXMLParser()
    let url = NSURL(string: "http://dexonline.ro/definitie/soapta/xml")!

    var element = String()
    var finalDefinitions = [String: NSMutableAttributedString]()

    init(delegate: DefintionFetching) {
        self.delegate = delegate
        super.init()
        parser.delegate = self
    }

    func fetch() {
        println("fetch called") // this gets called
        parser = NSXMLParser(contentsOfURL: url)!
        parser.parse()
    }

    func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: [NSObject: AnyObject]!) {
        // this doesn't get called
    }
}

And the VC calling the class:

class DexVC: UIViewController, DefintionFetching {
    lazy var definitionFetcher: DefinitionFetcher = DefinitionFetcher(delegate: self)

    func fetchingDidFinish(results: [String: NSMutableAttributedString]) { }

    @IBAction func doShit(sender: AnyObject) {
        definitionFetcher.fetch()
    }
}

Any help will be insanely high appreciated!


Solution

  • You replaced the parser property from the initial instance.

    func fetch(){
        println("fetch called")
        parser = NSXMLParser(contentsOfURL: url)!
    //  ^^^^^^^^^ HERE
        parser.parse()
    }
    

    so, parser.delegate = self in init is totally meaningless.

    try:

    func fetch(){
        println("fetch called")
        parser = NSXMLParser(contentsOfURL: url)!
        parser.delegate = self // <-- ADDED
        parser.parse()
    }