我正在使用Alamofire生成对随机网页的请求。我想获取标题故事的标题并将其保存在主线程中,以将其传递到MenuCell中。
import UIKit
import SwiftSoup
import Alamofire
class ArticleListScreen: UIViewController {
var index: Int = 0
var titles: [String] = []
var images: [UIImage] = [#imageLiteral(resourceName: "outside-page.png"),#imageLiteral(resourceName: "outside-page.png"),#imageLiteral(resourceName: "outside-page.png"),#imageLiteral(resourceName: "outside-page.png"),#imageLiteral(resourceName: "outside-page.png")]
let url: [NSURL] = [NSURL(string: "https://www.shreveporttimes.com/story/news/2019/03/12/only-louisiana-crawfish-pardoned-lent/3137805002/")!]
var articles: [Article] = []
var regular: [Regular] = []
var loaded = true
override func viewDidLoad() {
super.viewDidLoad()
parseHTML(id: "title")
articles = createArticleArray()
regular = createRegularArray()
}
func parseHTML(id: String){
var title: String = ""
Alamofire.request(url[0] as URL).responseString { response in
if let html: String = response.result.value {
NSLog(html)
do{
let doc: Document = try SwiftSoup.parse(html)
try title = doc.getElementsByTag(id).text()
NSLog("NEW SHIT: "+title)
}catch{
NSLog("None")
}
}
}
}
func createRegularArray() -> [Regular] {
var tempRegular: [Regular] = []
let regular1 = Regular(image:#imageLiteral(resourceName: "sps.jpg"), title: "NFL lawyer who claimed Super Bowl is 'rigged' is found dead")
tempRegular.append(regular1)
return tempRegular
}
func createArticleArray() -> [Article] {
var tempArticles: [Article] = []
for (image, title) in zip(images, titles) {
tempArticles.append(Article(image:image, title: title))
}
return tempArticles
}
}
extension ArticleListScreen: UITableViewDataSource, UITabBarDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return articles.count+regular.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if(indexPath.row == 0){
tableView.rowHeight = 270
tableView.separatorStyle = .singleLine
let article = regular[0]
let cell = tableView.dequeueReusableCell(withIdentifier: "RegularCell") as! RegularCell
cell.setArticle(article: article)
return cell
}
else if (indexPath.row == 1){
tableView.rowHeight = 100
//tableView.separatorStyle = .none
let article = articles[indexPath.row-1]
let cell = tableView.dequeueReusableCell(withIdentifier: "ArticleCell") as! ArticleCell
cell.setArticle(article: article)
return cell
}
else{
tableView.rowHeight = 90
//tableView.separatorStyle = .none
let article = articles[indexPath.row-1]
let cell = tableView.dequeueReusableCell(withIdentifier: "ArticleCell") as! ArticleCell
cell.setArticle(article: article)
return cell
}
}
}
请帮助。我似乎无法弄清楚如何在闭包之外获取数据。我知道闭包在不同的线程中运行,因此当我尝试在函数中返回数据时,数据永远都不准确。