繁体   English   中英

使用RxSwift将Alamofire请求绑定到表格视图

[英]Bind Alamofire request to table view using RxSwift

因此,我一直在研究RxSwift几天,并试图用它创建一个简单的应用程序。 我已将表的searchController绑定到结果,该结果将输入到cellForRowAt函数中。 如何将alamofire反应绑定到每个细胞? 我需要做哪些?

  • 使用RxAlamofire创建searchResultsArray
  • 将searchResultsArray更改为Variable并使用toObservable
  • 绑定responsesearchResultsArray以创建每个单元格。

我需要使用的功能是:

.bind(to: self.tableView.rx.items(cellIdentifier: "cell", cellType: UITableViewCell.self)) {  row, element, cell in
    cell.textLabel?.text = "something"
}

这是我当前的RxSwift代码:

let disposeBag = DisposeBag()
var searchResultsArray = [[String:String]]()  
searchController.searchBar.rx.text.orEmpty.filter { text in
        text.count >= 3
    }.subscribe(onNext: { text in
        searchRequest(search: text, searchType: "t:t") { response in
        self.searchResultsArray = response
        self.tableView.reloadData()
        }
    }).disposed(by: disposeBag)

这是我当前的单元格创建功能。 单击取消按钮时, showSearchResults更改。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: UITableViewCell = {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") else {
            return UITableViewCell(style: .subtitle, reuseIdentifier: "cell")
        }
        return cell
    }()
    if self.shouldShowSearchResults {
        cell.textLabel?.text = searchResultsArray[indexPath.row]["result"]!
        cell.detailTextLabel?.text = searchResultsArray[indexPath.row]["location"]!
    }

    return cell
}

这是我当前的api请求:

func searchRequest(search: String, searchType: String, completionHandler: @escaping ([[String: String]]) -> ()) {
    let payload: [String: Any] = [
        "q": search,
        "fq": searchType,
        "start": 0
    ]

    let url = URL(string: "https://www.athletic.net/Search.aspx/runSearch")!
    Alamofire.request(url, method: .post, parameters: payload, encoding: JSONEncoding.default).responseJSON { response in
        let json = response.data
        do {
            var searchResults: [[String: String]] = []
            let parsedJson = JSON(json!)
            if let doc = try? Kanna.HTML(html: parsedJson["d"]["results"].stringValue, encoding: .utf8) {
                for row in doc.css("td:nth-child(2)") {
                    let link = row.at_css("a.result-title-tf")!
                    let location = row.at_css("a[target=_blank]")!
                    let schoolID = link["href"]!.components(separatedBy: "=")[1]
                    searchResults.append(["location": location.text!, "result": link.text!, "id":schoolID])
                }
            }
            completionHandler(searchResults)
        } catch let error {
            print(error)
        }
    }
}

我想用RxSwift解决方案替换cellForRowAt。

根据您提供的代码,使用Rx将为您提供以下信息:

override func viewDidLoad() {
    super.viewDidLoad()

    searchController.searchBar.rx.text.orEmpty
        .filter { text in text.count >= 3 }
        .flatMapLatest { text in searchRequest(search: text, searchType: "t:t") }
        .bind(to: self.tableView.rx.items(cellIdentifier: "cell", cellType: UITableViewCell.self)) {  row, element, cell in
            if self.shouldShowSearchResults {
                cell.textLabel?.text = element["result"]!
                cell.detailTextLabel?.text = element["location"]!
            }
        }
        .disposed(by: disposeBag)
}

shouldShowSearchResults感觉shouldShowSearchResults 但是,否则看起来不错。

上面假设您将searchRequest包装在一个函数中,该函数返回如下所示的可观察值:

func searchRequest(search: String, searchType: String) -> Observable<[[String: String]]> {
    return Observable.create { observer in
        searchRequest(search: search, searchType: searchType, completionHandler: { result in
            observer.onNext(result)
            observer.onCompleted()
        })
        return Disposables.create()
    }
}

上面是一个标准模式,该模式将使用回调的函数包装到返回Observable的函数中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM