I am currently trying to parse a rest XML API response from a STANDS4 API...
The XML file would look something like this:
<results>
<result>
<quote>
To be free it is not enough to beat the system, one must beat the system every day.
</quote>
<author>Anonymous</author>
</result>
</results>
What I want to do is be able to print out the XML response and be able to assign the quote and author to a UILabel. What I currently have is the below code (I have my user ID and my token ID):
import UIKit
class ViewController: UIViewController,NSXMLParserDelegate {
var strXMLData:String = ""
var currentElement:String = ""
var passData:Bool=false
var passName:Bool=false
var parser = NSXMLParser()
@IBOutlet weak var lblNameData: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let url:String="http://www.stands4.com/services/v2/quotes.php?uid=youridhere&tokenid=youridherezf&searchtype=AUTHOR&query=Albert+Einstein"
let urlToSend: NSURL = NSURL(string: url)!
// Parse the XML
parser = NSXMLParser(contentsOfURL: urlToSend)!
parser.delegate = self
let success:Bool = parser.parse()
if success {
print("parse success!")
print(strXMLData)
lblNameData.text=strXMLData
} else {
print("parse failure!")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
currentElement=elementName;
if(elementName=="id" || elementName=="name" || elementName=="cost" || elementName=="description")
{
if(elementName=="name"){
passName=true;
}
passData=true;
}
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
currentElement="";
if(elementName=="id" || elementName=="name" || elementName=="cost" || elementName=="description")
{
if(elementName=="name"){
passName=false;
}
passData=false;
}
}
func parser(parser: NSXMLParser, foundCharacters string: String) {
if(passName){
strXMLData=strXMLData+"\n\n"+string
}
if(passData)
{
print(string)
}
}
func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) {
NSLog("failure error: %@", parseError)
}
}
I currently get the response that the parse was a success but nothing is printed out. I got the above code from this tutorial: http://ashishkakkad.com/2014/10/xml-parsing-in-swift-language-ios-9-nsxmlparser/
So there is most likely some changes I need to make to work with my current API, but I'm not sure what exactly to do.
Any help is appreciated!