When should you call NSXMLParser.parse() on your NSStream?

152 views Asked by At

I have a NSXMLParser object. I'm running an XMPP stream.

Does .parse() need to be called each time I receive a message or just once?

Here's a parse of relevant code in the NSStream:

func connectToSocket(host: String, port: Int) {

    NSStream.getStreamsToHostWithName(host, port: port, inputStream: &(self.input), outputStream: &(self.output))

    self.input!.delegate  = self
    self.output!.delegate = self



    //self.input!.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
    //self.output!.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
    self.input!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
    self.output!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)

    self.input!.open()
    self.output!.open()

    parser = NSXMLParser(stream: input!)
    parser!.delegate = self
}
1

There are 1 answers

1
xnyhps On

.parse() is a synchronous operation, so it will block until it has parsed the entire stream. You'll have to call parse from a different thread (or dispatch queue), or schedule the input stream in a different runloop.

See here for how to create a dispatch queue for the parser, and here for how to use the input stream from a different queue.