Swift:在tableView中搜索JSON数据

达菲DD

我正在尝试做一个从JSON获取数据的应用程序。现在我参与了搜索,问题是搜索不起作用(显示所有数据)。请帮我。这是代码。

在这里您可以看到项目

项目

JSON数据的链接是:http : //jsonplaceholder.typicode.com/photos

import UIKit
import Alamofire
import AlamofireImage
import SwiftyJSON

class ViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate {


    @IBOutlet weak var searchbarValue: UISearchBar!
    weak open var delegate: UISearchBarDelegate?
    @IBOutlet weak var tableView: UITableView!


        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
                self.searchbarValue?.delegate = self
            self.searchBarSearchButtonClicked(self.searchbarValue)
    }
    var albumArray = [AnyObject]()
    var searchURL = String()
    typealias JSONStandard = [String : AnyObject]
    var url = ("https://jsonplaceholder.typicode.com/photos")
    func callAlamo(url : String){
        Alamofire.request(url).responseJSON(completionHandler: {
            response in
            self.parseData(JSONData: response.data!)
        })
    }

    func parseData(JSONData : Data) {
        do {
            Alamofire.request("https://jsonplaceholder.typicode.com/photos").responseJSON { (responseData) -> Void in
                if((responseData.result.value) != nil) {
                    let swiftyJsonVar = JSON(responseData.result.value!)
                    //
                    if let resData = swiftyJsonVar[].arrayObject {
                        self.albumArray = resData as [AnyObject]; ()

                    }
                    if self.albumArray.count > 0 {
                        self.tableView.reloadData()
                    }
                }
            }
        }
        catch{
            print(error)
        }
    }
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

        let keywords = searchbarValue.text
        let finalKeywords = keywords?.replacingOccurrences(of: " ", with: "+")


        searchURL = "https://jsonplaceholder.typicode.com/photos?q=\(finalKeywords!)"

        //print(searchURL)

        callAlamo(url: searchURL)
        self.view.endEditing(true)

    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return albumArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? CostumTableViewCell

        let title = albumArray[indexPath.row]
        cell?.titleLabel?.text = title["title"] as? String

        let imageUrl = title["thumbnailUrl"] as? String
        //print(imageUrl)

        let urlRequest = URLRequest(url: URL(string: imageUrl!)!)
        Alamofire.request(urlRequest).responseImage { response in


            if let image = response.result.value {
               // print("image downloaded: \(title["url"])")
                cell?.url?.image = image

            }
        }
        return cell!
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        performSegue(withIdentifier: "showDetails", sender: self)
    }
//    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//        let indexPath = self.tableView.indexPathForSelectedRow?.row
//
//        let vc = segue.destination as! DetailsViewController
//
//    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let indexPath = self.tableView.indexPathForSelectedRow

        let cell : CostumTableViewCell = self.tableView.cellForRow(at: indexPath!) as! CostumTableViewCell

        let vc = segue.destination as! DetailsViewController

        vc.image2 = cell.url.image!
        vc.title2 = cell.titleLabel.text!
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

预先感谢您的帮助。

Waqas苏丹|

我能在代码中找到错误的地方。请修复它。我希望你能得到你的结果。如果不是,请分享代码。我会尽力帮助您。谢谢

 func callAlamo(url : String){
    fetchDataFromServiceURL(url)
}

func fetchDataFromServiceURL(_ serviceRequestURl:String) {
    do {
        Alamofire.request(serviceRequestURl).responseJSON { (responseData) -> Void in
            if((responseData.result.value) != nil) {
                let swiftyJsonVar = JSON(responseData.result.value!)
                //
                if let resData = swiftyJsonVar[].arrayObject {
                    self.albumArray = resData as [AnyObject]; ()

                }
                if self.albumArray.count > 0 {
                    self.tableView.reloadData()
                }
            }
        }
    }
    catch{
        print(error)
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章