ios - 在 TableView 中仅显示一次 json 数组中的重复元素 swift

标签 ios json swift uitableview

我正在制作一个 iOS 应用程序,显示哪些电影是在某些城市拍摄的。我试图仅在一个 TableView 中显示重复的城市一次,并且仅在另一个 TableView 中显示在所选城市拍摄的电影。我的所有数据都是从我创建的本地 JSON 文件中读取的。目前,我的城市 TableView 显示所有重复的城市,我的电影表显示 JSON 文件中的所有电影。我希望城市表中没有重复的城市,并且只有从城市表中选择城市时在该城市拍摄的电影。

what my app currently displays

import UIKit

class cityTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    var movieObject = [Movies]()

    @IBOutlet weak var cityTable: UITableView!
    @IBOutlet weak var movieTable: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.cityTable.rowHeight = 50
        self.movieTable.rowHeight = 50

        cityTable.delegate = self
        cityTable.dataSource = self

        movieTable.delegate = self
        movieTable.dataSource = self

        readJson ()
    }

    func readJson() {
        guard let path = Bundle.main.path(forResource: "movies", ofType: "json") else {return}
        let url = URL(fileURLWithPath: path)
        let task = URLSession.shared.dataTask(with: url) {(data,response,error) -> Void in
        // If there is an error, print the error
            if error != nil {
                print(error!)
                return
            } // end if

            do{
                let data = try Data(contentsOf: url)
                let json = try JSONSerialization.jsonObject(with: data, options: []) as AnyObject

                let array = json as? [[String:Any]]

                for eachMovie in array! {
                    if let movie = Movies(json: eachMovie)
                    {
                        self.movieObject.append(movie)
                    }

                    print(self.movieObject)
                }
                DispatchQueue.main.async{self.cityTable.reloadData()}
                DispatchQueue.main.async{self.movieTable.reloadData()}
            } catch {print(error)}
        }
        task.resume()
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let mov:Movies = movieObject[indexPath.row]

        if tableView == cityTable
        {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cityCell", for: indexPath) as! cityTableViewCell

            //let cityArray = mov.City
            //let index = cityArray?.first

            //print("City: \(String(describing: index))")
            var uniqueCity = [String]()

            for elem in mov.City! {
                if !uniqueCity.contains(elem)
                {
                    uniqueCity.append(elem)
                }
            }

            //print(uniqueCity)
            let index = uniqueCity.first

            cell.cityLabel.text = index

            print("City: \(String(describing: index))")

            return cell
        }
        else //if tableView == movieTable
        {
            let cell = tableView.dequeueReusableCell(withIdentifier: "movieCell", for: indexPath) as! movieTableCell

            cell.movieLabel!.text = mov.Title

            return cell
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.

        let destVC = segue.destination as! movieViewController
        if let indexPath = self.movieTable.indexPathForSelectedRow {
            let mov:Movies = movieObject[indexPath.row]

            destVC.tvCity = mov.City!
            destVC.tvTitle = mov.Title
            destVC.tvDirector = mov.Director
            destVC.tvYear = mov.Year
            destVC.tvImage = mov.Image
            destVC.tvWebsite = mov.Website
            destVC.tvAddress = mov.Addresses!
        }
    }
}

//我的 json 文件

     [
  {
  "id": "1",
  "City": ["San Francisco, CA", "Long Beach, CA"],
  "Title": "Titanic",
  "Director": "James Cameron",
  "Year": "1997",
  "Image": "Titanic.jpg",
  "Website": "https://www.imdb.com/title/tt0120338/",
  "Address": [
              "Pier 45, Fisherman's Wharf, San Francisco, CA 94133",
              "4000 E Olympic Plaza Long Beach, CA 90803"
              ]
  },
  {
  "id": "2",
  "City": ["Los Angeles, CA"],
  "Title": "Fast And Furious",
  "Director": "Justin Lin",
  "Year": "2009",
  "Image": "f&f1.jpg",
  "Website": "https://www.imdb.com/title/tt1013752/",
  "Address": [
              "3680 Wilshire Boulevard, Midtown, Los Angeles, CA 90010",
              "1318 E 7th St Los Angeles, CA 90021",
              "3385 W 8th St, Los Angeles, CA 90005",
              "722 E Kensington Rd, Los Angeles, CA 90026"
              ]
  },
  {
  "id": "3",
  "City": ["Miami, FL"],
  "Title": "2 Fast 2 Furious",
  "Director": "John Singleton",
  "Year": "2003",
  "Image": "2f2f.jpg",
  "Website": "https://www.imdb.com/title/tt0322259/",
  "Address": [
              "318 NW 23rd St, Miami, FL 33127",
              "401 North Miami Avenue, Miami, FL 33136",
              "3301 Rickenbacker Causeway, Key Biscayne, FL 33149",
              "1 Ocean Drive, South Miami Beach, FL 33139",
              "3555 SW 8th Street, East Coral Gables, FL 33135",
              "1200 South Crandon Boulevard, Key Biscayne, FL 33149"
              ]
  },
  {
  "id": "4",
  "City": ["Los Angeles, CA"],
  "Title": "The Fast and The Furious",
  "Director": "Rob Cohen",
  "Year": "2001",
  "Image": "tf&tf.jpg",
  "Website": "https://www.imdb.com/title/tt0232500/",
  "Address": [
              "1000 Vin Scully Avenue, Los Angeles, CA 90012",
              "42505 Pacific Coast Highway, Malibu, CA 90265",
              "N Orange Dr, Los Angeles, CA 90038",
              "Center St, Los Angeles, CA 90021"
              ]
  },
  {
  "id": "5",
  "City": ["Los Angeles, CA" ],
  "Title": "The Fast And The Furious: Tokyo Drift",
  "Director": "Justin Lin",
  "Year": "2006",
  "Image": "tokyodrift.jpeg",
  "Website": "https://www.imdb.com/title/tt0463985/",
  "Address": [
              "San Gabriel Canyon Rd, Azusa, CA 91702",
              "12630 Hawthorne Blvd, Hawthorne, CA 90250",
              "2001 Santa Fe Ave, Long Beach, CA 90810"
              ]
  },
  {
  "id": "6",
  "City": ["Los Angeles, CA", "Atlanta, GA"],
  "Title": "Furious 7",
  "Director": "James Wan",
  "Year": "2015",
  "Image": "f&f7.jpeg",
  "Website": "https://www.imdb.com/title/tt2820852/",
  "Address": [
              "722 E Kensington Rd, Los Angeles, CA 90026",
              "248 Oakland Ave SE, Atlanta, GA 30312",
              "Mahers Quarry Rd, Stockbridge, GA 30281"
              ]
  },
  {
  "id": "7",
  "City": ["Miami, FL", "New York, NY"],
  "Title": "Scarface",
  "Director": "Brian de Palma",
  "Year": "1983",
  "Image": "scarface.jpg",
  "Website": "https://www.imdb.com/title/tt0086250/",
  "Address": [
              "728 Ocean Drive, Miami Beach, FL 33139",
              "4441 Collins Avenue, Miami, FL 33140",
              "E 41st St, New York, NY 10017"
              ]
  },
  {
  "id": "8",
  "City": ["Chicago, IL"],
  "Title": "Batman Begins",
  "Director": "Christopher Nolan",
  "Year": "2005",
  "Image": "BmanBegins.jpg",
  "Website": "https://www.imdb.com/title/tt0372784/",
  "Address": [
              "141 W Jackson Blvd, Chicago, IL 60604",
              "200 N Franklin St, Chicago, IL 60606",
              "35 E Upper Wacker Dr, Chicago, IL 60601"
              ]
  },
  {
  "id": "9",
  "City": ["Detroit, MI", "Chicago, IL", "Los Angeles, CA"],
  "Title": "Batman v Superman: Dawn Of Justice",
  "Director": "Zack Snyder",
  "Year": "2016",
  "Image": "BmanvSman.jpg",
  "Website": "https://www.imdb.com/title/tt2975590/",
  "Address": [
              "2301 Clarkston Road, Orion Charter Township, MI 48360",
              "547 East Circle Drive, East Lansing, MI 48824",
              "1106 West Lawrence Avenue, Chicago, IL 60640",
              "1301 Avenida Cesar Chavez, Monterey Park, CA 91754",
              "600 Randolph Street, Detroit, MI 48226"
              ]
  },
  {
  "id": "10",
  "City": [ "Chicago, IL"],
  "Title": "The Dark Knight",
  "Director": "Christopher Nolan",
  "Year": "2008",
  "Image": "DKnight.jpg",
  "Website": "https://www.imdb.com/title/tt0468569/",
  "Address": [
              "1665 N Sedgwick St, Chicago, IL 60614",
              "404 W Harrison St, Chicago, IL 60607",
              "200 W Randolph St, Chicago, IL 60606",
              "330 N Wabash Ave, Chicago, IL 60611"
              ]
  },
  {
  "id": "11",
  "City": ["Los Angeles, CA", "New York, NY"],
  "Title": "The Dark Knight Rises",
  "Director": "Christopher Nolan",
  "Year": "2012",
  "Image": "DKnightRises.jpg",
  "Website": "https://www.imdb.com/title/tt1345836/",
  "Address": [
              "725 5th Ave, New York, NY 10022",
              "23 Wall St, New York, NY 10005",
              "433 S Spring St, Los Angeles, CA 90013"
              ]
  },
  {
  "id": "12",
  "City": ["Los Angeles, CA"],
  "Title": "Superman Returns",
  "Director": "Bryan Singer",
  "Year": "2006",
  "Image": "SmanReturns.jpg",
  "Website": "https://www.imdb.com/title/tt0348150/",
  "Address": [
              "1000 Vin Scully Avenue, Los Angeles, CA 90012"
              ]
  },
  {
  "id": "13",
  "City": ["Los Angeles, CA"],
  "Title": "Suicide Squad",
  "Director": "David Ayer",
  "Year": "2016",
  "Image": "SSquad.jpg",
  "Website": "https://www.imdb.com/title/tt1386697/",
  "Address": [
              "617 S Olive St, Los Angeles, CA 90014"
              ]
  },
  {
  "id": "14",
  "City": ["Chicago, IL"],
  "Title": "Home Alone",
  "Director": "Chris Columbus",
  "Year": "1990",
  "Image": "homealone.jpg",
  "Website": "https://www.imdb.com/title/tt0099785/",
  "Address": [
              "671 Lincoln Ave, Winnetka, IL 60093",
              "1024 Lake Ave, Wilmette, IL 60091",
              "10000 W O'Hare Ave, Chicago, IL 60666"
              ]
  }
  ]

最佳答案

你可以试试这个:

    var uniqueCity = [String]() // make this global

    func readJson() {
         guard let path = Bundle.main.path(forResource: "movies", ofType: "json") else {return}
         let url = URL(fileURLWithPath: path)
         let task = URLSession.shared.dataTask(with: url) {(data,response,error) -> Void in
        // If there is an error, print the error
        if error != nil {
            print(error!)
            return
        } // end if

        do{
            let data = try Data(contentsOf: url)
            let json = try JSONSerialization.jsonObject(with: data, options: []) as AnyObject

            let array = json as? [[String:Any]]

            for eachMovie in array! {
                if let movie = Movies(json: eachMovie)
                {
                    let city = movie.tvCity
                    if (!self.uniqueCity.contains(city)) { // change here
                        self.uniqueCity.append(city)
                    }
                    self.movieObject.append(movie)
                }

                print(self.movieObject)
            }
            DispatchQueue.main.async{self.cityTable.reloadData()}
            DispatchQueue.main.async{self.movieTable.reloadData()}
        } catch {print(error)}
    }
    task.resume()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if (tableView == cityTable) { // change here
        return uniqueCity.count
    }
    return movieObject.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let mov:Movies = movieObject[indexPath.row]

    if tableView == cityTable
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cityCell", for: indexPath) as! cityTableViewCell

        //print(uniqueCity)
        let index = uniqueCity[indexPath.item] // change here

        cell.cityLabel.text = index

        print("City: \(String(describing: index))")

        return cell
    }
    else //if tableView == movieTable
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "movieCell", for: indexPath) as! movieTableCell

        cell.movieLabel!.text = mov.Title

        return cell
    }
}

关于ios - 在 TableView 中仅显示一次 json 数组中的重复元素 swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50959346/

相关文章:

iOS模拟器应用位置

ios - 如何只能在UICollectionView中的Indexpath.section之间滚动排除indexpath.row

swift - 从 do-catch 语句返回字符串

ios - 将函数转换为扩展时遇到问题

ios - 传递参数以将项目发布到 Facebook

ios - ScrollView 在模拟器中无法正常工作

iOS 从 nib 加载 View

json - Bash 脚本在 Json 中动态添加新的键值对

c# - Web Api 2 不反序列化 JSON

java - 从android应用程序中的php文件读取JSON数据