Как перенести данные из закрытия Alamofire в основной поток - PullRequest
0 голосов
/ 13 марта 2019

Я использую 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
        }
    }
}

Пожалуйста, помогите.Я не могу понять, как получить данные за пределами закрытия.Я понимаю, что замыкания выполняются в другом потоке, поэтому данные никогда не бывают точными, когда я пытаюсь вернуть их в функцию.

1 Ответ

0 голосов
/ 13 марта 2019

Попробуйте таким образом, также я бы порекомендовал прочитать о завершениеHandler .

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
    }
...