misctp asdas misctp asdas - 5 months ago 28
iOS Question

Unable to extract url value from enclosure tag rss xml with SWIFT 2

I am having difficulties with extracting the url contents of the enclosure tag within RSS Feed. Im developing on Xcode 7 Swift 2.

My NSXMLDelegate Parsing code is as below:

func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
eName = elementName
if elementName == "item" {
postTitle = String()
postLink = String()
postDate = String()
postImageUrl = String()
}
}


Below is the relevant source code responsible for parsing the RSS XML feed

func parser(parser: NSXMLParser, foundCharacters string: String) {
let data = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
if (!data.isEmpty) {
print("eName Start")
print(eName)
print(data,"DATAAAA")
print("eName END")
if eName == "title" {
postTitle += data//TEST OK
} else if eName == "link" {
postLink += data//TEST OK
} else if eName == "pubDate" {

postDate += data//TEST OK
}
else if eName == "enclosure"{
print(data)//THIS IS EMPTY WHY !?
print("enc details")
postImageUrl += data
}
}
}


As above, I was able to extract the "title" , "pubDate" and "link" tags from the RSS Feed but not the enclosure tag.
When I attempt to dump out the data upon detecting "enclosure" the data returned was empty.

I suspect the problem lies with this line of code where i am not filtering the RSS objects correctly.

let data = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())


The source of the RSS feed is : www.securitymagazine.com/rss/15

Can anybody offer some insight to this please? I appreciate it very much !

Answer

The "enclosure" element in the RSS is like this:

<enclosure url="http://www.securitymagazine.com/ext/resources/SEC/2016/0616/Boschdata.jpg?1467317413" type="image/jpeg" length="280480"/>

The url is included as an attribute of the element, not a character (#text) data following the opening tag. You can access element attributes in parser(_:didStartElement:...) method. So, you need to modify the method like this:

func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
    eName = elementName
    switch elementName {
    case "item":
        postTitle = String()
        postLink = String()
        postDate = String()
        postImageUrl = String()
    case "enclosure":
        if let urlString = attributeDict["url"] {
            //...use `urlString` appropriately
            print(urlString)
            print("enc details")
            postImageUrl += urlString
        } else {
            print("malformed element: enclosure without url attribute")
        }
    //...cases for other element name
    default:
        //...
        break
    }
}