我正在尝试从alamofire变量中更改全局变量,但我遇到了问题。这是我的代码:
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)
}
当我在这里打印self.projects时,我得到一个空数组,但是当我在httpRequest函数中打印它时,我得到了正确的数据。我没有在for循环中设置全局变量项目吗?我怎样才能获得该函数之外的值?我已经尝试过在SO上找到的所有内容但没有成功。非常感谢任何帮助。
更多信息,请参阅我的httpRequest函数:
func httpRequest(_ section: String, completion: @escaping (String) -> Void) {
Alamofire.request(section, method: .get).responseString { response in
completion(response.result.value!)
}
}
答案 0 :(得分:1)
假设xml [" rss"] [" channel"] [" item"]不是零...
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
}