Casey
Casey

Reputation: 164

UISearchBar and JSON Data

This is my first time using a UISearchBar and it is proving to confuse me.

I think my biggest problem here is not understanding how JSON is stored and displayed.

I have my JSON data stored as:

    [{
  "referralId" : "v-1519014616",
  "name" : "Empire State Building",
  "storeId" : "",
  "hereNow" : {
    "count" : 2,
    "summary" : "2 people are here",
    "groups" : [
      {
        "count" : 2,
        "type" : "others",
        "name" : "Other people here",
        "items" : [

        ]
      }
    ]
  },
  "stats" : {
    "tipCount" : 1105,
    "checkinsCount" : 185916,
    "usersCount" : 129661
  },
  "venueRatingBlacklisted" : true,
  "beenHere" : {
    "lastCheckinExpiredAt" : 0
  },
  "specials" : {
    "count" : 0,
    "items" : [

    ]
  },
  "venuePage" : {
    "id" : "64514349"
  },
  "verified" : true,
  "location" : {
    "state" : "NY",
    "neighborhood" : "Midtown Manhattan, New York, NY",
    "crossStreet" : "btwn 33rd & 34th St",
    "lat" : 40.748469532965927,
    "address" : "350 5th Ave",
    "cc" : "US",
    "city" : "New York",
    "postalCode" : "10118",
    "formattedAddress" : [
      "350 5th Ave (btwn 33rd & 34th St)",
      "New York, NY 10118"
    ],
    "lng" : -73.985513794430119,
    "distance" : 17,
    "country" : "United States"
  },
  "hasPerk" : false,
  "id" : "43695300f964a5208c291fe3",
  "categories" : [
    {
... etc
},

I have this stored in an array titled locations and I am trying to filter through it with a search bar.

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        let name = self.locations[0]["name"].string
        filteredLocations = locations.filter { names in
            return (name!.lowercased().contains(searchText.lowercased()))
        }

        tableView.reloadData()
    }

Now, obviously, name is only going to search for the item in the array. How would I be able to filter through every location's name key to properly filter?

Upvotes: 0

Views: 137

Answers (1)

Pradeep Kashyap
Pradeep Kashyap

Reputation: 961

try this one ... don't take name first from location array...

 let filterArr = locations.filter {
        return (($0["name"] as! String).lowercased().contains(searchText.lowercased())))
    }

use this one to get the search result

Upvotes: 2

Related Questions