Trying to add a search for location feature in my app, but it doesn't work

Viewed 6

I'm making a restaurant review app in XCode similar to yelp, and I wanted to add a feature to let users search for locations. When you open up the app, it gets your location and displays restaurant results based on your location with this code:

locationService.newLocation = { [weak self] result in
            switch result {
            case .success(let location):
                self?.loadBusinesses(with: location.coordinate)
            case .failure(let error):
                print(error.localizedDescription)
            }

I added a search bar that searches for locations and prints out the coordinates, and it prints out fine. Here is the code for this part:

let searchRequest = MKLocalSearch.Request()
        searchRequest.naturalLanguageQuery = searchBar.text
        
        let activeSearch = MKLocalSearch(request: searchRequest)
        
        activeSearch.start { (response, error) in
            if response == nil {
                print("Error")
            }
            else {
                let latitude = (response?.boundingRegion.center.latitude)!
                let longitude = (response?.boundingRegion.center.longitude)!
                print(latitude, longitude)
                let coords: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)

So now, using the coordinates that the search bar just gave me, I'm trying to find a way to display restaurants near the coordinate that was just searched. Here is what I've tried so far:

//                FIRST ATTEMPT
//                let appdel = AppDelegate()
//                let searchbizz: () = appdel.loadBusinesses(with: coords)
                
                //SECOND ATTEMPT
//                func searchbiz() {
//                    appdel.loadBusinesses(with: coords)
//                print("hello")
//                }
                
                //THIRD ATTEMPT
                func searchbizy() {
                    print("hello there")
                    self.locationService.newLocation = { [weak self] result in
                        switch result {
                        case .success(_):
                            AppDelegate().loadBusinesses(with: coords)
                        case .failure(let error):
                            print(error.localizedDescription)
                        }
                    }
                }
//                searchbiz()
//                searchbizy()
                self.tableView.reloadData()

Essentially, I'm trying to call a function that was in AppDelegate and originally pulled the user's location and displayed the restaurants, and replace the orignal location with the coordinates from the search. Is there something I'm doing wrong or missing here?

0 Answers
Related