ios - 如何将数据从Alamofire闭包迁移到主线程

标签 ios swift alamofire

我正在使用 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
        }
    }
}

请帮忙。我似乎无法弄清楚如何在闭包之外获取数据。我知道闭包在不同的线程中运行,因此当我尝试在函数内返回数据时,数据永远不准确。

最佳答案

尝试这种方式,我也建议阅读有关 completionHandler 的文章。

func parseHTML(id: String, completionHandler: @escaping (String) -> Void){
    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)
                completionHandler(title)
            }catch{
                NSLog("None")
                completionHandler("None")
            }
        }
    }
}

    //Useage
    parseHTML(id: "") { result in
        self.title = result
    }

关于ios - 如何将数据从Alamofire闭包迁移到主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55137656/

相关文章:

ios - SwiftUI 主列表可滚动标题 View 没有部分?

iOS DIsptchqueue.global 错误

ios - iOS8 中 UITextField 默认的 borderColor 是什么?

ios - 出现键盘时向上移动 TextField/View,但前提是隐藏了 Text Field

swift - Alamofire,在参数中上传带有结构的MultipartFormData

ios - 由于 TIC SSL 信任错误,无法使用 Alamofire 发出请求

ios - UISplitViewController 中的 UITabViewController

ios - OneSignal Push for array of vales

ios - 恢复购买 - Swift

ios - 如何将 Json 数据推送到 UITableView 中的标签?