I am trying to change a global variable from within an alamofire variable but am having issues doing it. Here is my code:
var projects = [[String]]()
var xmlToParse = String()
var postTitle = String()
var postLink = String()
override func viewDidLoad() {
super.viewDidLoad()
httpRequest("https://www.hello.com/feed") { response in
self.xmlToParse = response as String
let xml = SWXMLHash.parse(self.xmlToParse)
for elem in xml["rss"]["channel"]["item"].all {
self.postTitle = elem["title"].element!.text
self.postLink = elem["link"].element!.text
self.projects.append([self.postTitle, self.postLink])
}
}
print(self.projects)
}
When I print self.projects here, i get an empty array, however when I print it inside the httpRequest function I get the proper data. Am I not setting the global variable projects within the for loop? How can I get the value outside of that function? I have tried everything I found on SO with no success. Any help is greatly appreciated.
Just for more info, here is my httpRequest function:
func httpRequest(_ section: String, completion: @escaping (String) -> Void) {
Alamofire.request(section, method: .get).responseString { response in
completion(response.result.value!)
}
}
Assuming that xml["rss"]["channel"]["item"] is not nil...
override func viewDidLoad() {
super.viewDidLoad()
httpRequest("https://www.hello.com/feed") { response in
self.xmlToParse = response as String
let xml = SWXMLHash.parse(self.xmlToParse)
for elem in xml["rss"]["channel"]["item"].all {
self.postTitle = elem["title"].element!.text
self.postLink = elem["link"].element!.text
self.projects.append([self.postTitle, self.postLink])
}
self.setup()
}
}
func setup() {
// Your logic here
}