import UIKit
import CoreLocation
class RestaurantSearchViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var tableView: UITableView!
let locationManager = CLLocationManager()
var restaurants: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
tableView.dataSource = self
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let userLocation = locations.first else {
return
}
let latitude = userLocation.coordinate.latitude
let longitude = userLocation.coordinate.longitude
let apiUrl = "https://api.example.com/restaurants?lat=\(latitude)&lon=\(longitude)"
guard let url = URL(string: apiUrl) else { return }
URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print("Error: \(error)")
} else if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
if let restaurantsArray = json?["restaurants"] as? [String] {
self.restaurants = restaurantsArray
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
} catch {
print("JSON parsing error: \(error)")
}
}
}.resume()
}
}
extension RestaurantSearchViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return restaurants.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RestaurantCell", for: indexPath)
cell.textLabel?.text = restaurants[indexPath.row]
return cell
}
}