RyanTCB RyanTCB - 2 months ago 20
Swift Question

NSXMLParser contentsOfURL Vs Data

When parsing an XML file from a server I have always used "

init(data: Data)

let url = URL(string: urlString)
let data = NSData(contentsOf: url!)
let parser = XMLParser(data: data as! Data)

I read the docs and see this method "
init?(contentsOf: URL)

let url = URL(string: urlString)
let parser = XMLParser(contentsOf: url!)

Question is then am I unnecessarily converting to a data object from the URL contents, and I may as well just initialise from the URL? Or, is there any merit to creating the data object and parsing from that?


There is no semantic difference between the two variants.

For http(s) urls you should prefer init(data:) or XMLParser(data:), but you should not load you data with NSData(contentsOf:). The reason is that the contentsOf: variants will block the current thread with a synchronous request. You should instead load the data asynchronously with NSURLSession.

You should use XMLParser(contentsOf:) and Data(contentsOf:) only for file urls.