I am building XML parser in swift and I faced several problems. First: Xcode sometimes throws new errors such as BAD_ACCESS and sometimes works perfectly. Second: same situation, I sometimes get error on converting pubDate which get as string to NSDate
and sometimes it works absolutely perfect. The thing is that I am parsing the data from several links using for
loop and in that loop I have dispatch with Utility
class. I guess it could be the problem.
Here is the code of my NSXMLParserDelegate
:
class Parser: NSObject, NSXMLParserDelegate {
var title: String!
var link: String!
var pubDate: String!
var currentElement = String()
var isInItem = false
var URL: String!
var lastBuildDate: String!
var parser: NSXMLParser!
var delegate: ParserDelegate!
var currentSource = [String]()
var all = [Item]()
var count = 0
init(currentSource: [String]) {
self.currentSource = currentSource
}
func parse(){
all.removeAll()
count = 0
for url in currentSource {
dispatch(queue: .Background) {
self.parser = NSXMLParser(contentsOfURL: NSURL(string: url)!)
self.parser.delegate = self
self.parser.parse()
}
}
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
if elementName == "item"{
isInItem = true
link = ""
title = ""
pubDate = ""
}
else if elementName == "lastBuildDate"{
lastBuildDate = String()
}
if isInItem{
switch elementName{
case "pubDate":
pubDate = String()
currentElement = "pubDate"
case "title":
title = String()
currentElement = "title"
case "link":
link = String()
currentElement = "link"
default:
break
}
}
}
func parser(parser: NSXMLParser, foundCharacters string: String) {
if isInItem{
switch currentElement {
case "pubDate":
pubDate = pubDate + string
case "title":
title = title + string
case "link":
link = link + string
default:
break
}
}
else if currentElement == "lastBuildDate"{
lastBuildDate = lastBuildDate + string
}
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if isInItem{
currentElement = ""
}
if elementName == "item" {
isInItem = false
let item = Item()
item.link = link
item.title = title
item.timeAgo = Double.time(NSDate().timeIntervalSinceDate(NSDate.getDate(pubDate)))
item.timeDiff = NSDate().timeIntervalSinceDate(NSDate.getDate(pubDate))
all.append(item)
}
}
func parserDidEndDocument(parser: NSXMLParser) {
count += 1
if count == currentSource.count{
all.sortInPlace({$0.timeDiff < $1.timeDiff})
delegate.parseArray(all)
print(all.count)
}
}
}