0

So, let me explain as easy and short as I can...
I am trying to parse a xml file from a url using swift, with my regular method:

if let parser = NSXMLParser(contentsOfURL: xml) {
        parser.delegate = self

        let success:Bool = parser.parse()

        if success {
            print("parse success")

        } else {
            print("parse failure!")
        }
    }   

It works, but when encountering special characters such as accents, everything becomes a mess, so i found here that if instead of parsing directly the url i used NSData with encoding that would not happen.
As I am trying for the first time swift 2.0 and error handling with catch and try, don't know much about it. Here is my code:

do{
        let dataString = try String(contentsOfURL: XML, encoding: NSUTF8StringEncoding)
        let data:NSData = dataString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!

        if let parser = NSXMLParser(data: data) as NSXMLParser! {
            parser.delegate = self

            let success:Bool = parser.parse()

            if success {
                print("parse success")

            } else {
                print("parse failure!")
            }
        }

    }catch {
        print("catch failure!")
    }

But this always returns "catch failure!", the url is allright and working, with the other method its working (except for the special characters) i'm really at a loss.

Thank you very much in advance!

Ponchotg
  • 1,195
  • 1
  • 14
  • 25

1 Answers1

0

Following another answer Here I was able to fix the issue.

Instead of using:

func parser(parser: NSXMLParser, foundCharacters string: String) {
    if (currentElement != ""){
            currentString = string

    }

}

I used:

func parser(parser: NSXMLParser, foundCharacters string: String) {
    if (currentElement != ""){
            currentString += string

    }

}

and everything worked as it should've!

Community
  • 1
  • 1
Ponchotg
  • 1,195
  • 1
  • 14
  • 25