Swift:在tableView中搜索JSON数据

时间:2018-07-02 07:36:48

标签: ios swift alamofire swift4

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

在这里您可以看到项目

Project

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


}

如果您能帮助我,请先谢谢您。

1 个答案:

答案 0 :(得分:4)

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

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