Joakim Joakim - 6 months ago 9
iOS Question

var inside class is empty when accessing it within the same class

I have a class that will download and parse some xml data.
When pressing the button I create an instance of the class and call a function in that class.

The function in the class will download some xml data and assign it to a variable inside the class. Then the function will call a another function to begin parsing the data within the same class. But when this function tries to parse the variable with the xml data it is empty.

My question is why would the variable be empty when accessing it from another function within the same class?

ViewController:
@IBAction func searchFieldAction(sender: AnyObject) {
let bibSearch: bibSok = bibSok()
if let searchQ = searchfield.text {
bibSearch.bookSearch(String(searchQ))
}
}


Nothing wrong here ^

class bibSok: NSObject, NSXMLParserDelegate {
var xmlData:NSData = NSData()

func bookSearch(let stringQuery: String){
self.xmlData = NSData()
let url = "urlToGetXMLdata"

Alamofire.request(.GET, url!).validate().response { (request, response, data, error) in
print(request) //url is looking good and everything is fine
print(response) //Looking good. 200OK
print(error) //Nothing to see here
print(data!) //Gives xml data. Everything is good
self.xmlData = data! //assign data to the variable. Great so far
}
self.beginParsing()
}
func beginParsing(){
print("Begin parsing")
print(self.xmlData) //Empty as f*$%. <>
self.parser = NSXMLParser(data: self.xmlData) //Will not begin parse because it is empty
self.parser.delegate = self
self.parser.parse()

}



}


Obviously there is more code, but I brought you the code where the problem is.

Answer

The Alamofire request method must be asynchronous. That means that it returns immediately, before the data is available.

The idea with an async method with a completion block like this is that the completion block gets called once the request is complete. You need to move your call to beginParsing() inside the completion block:

Alamofire.request(.GET, url!).validate().response { (request, response, data, error) in
    print(request) //url is looking good and everything is fine
    print(response) //Looking good. 200OK 
    print(error) //Nothing to see here
    print(data!) //Gives xml data. Everything is good
    self.xmlData = data!  //assign data to the variable. Great so far        
    self.beginParsing()
}