Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // ViewController.swift
- // Hospital
- //
- // Created by Wojciech Miśta on 14/10/2019.
- // Copyright © 2019 Wojciech Miśta. All rights reserved.
- //
- import UIKit
- import CoreLocation
- import Foundation
- struct Hospital {
- let lat: Double
- let long: Double
- let name: String
- let distance: Double
- let address: String
- let tags: [String]
- }
- class ViewController: UIViewController, CLLocationManagerDelegate, UITableViewDelegate, UITableViewDataSource {
- @IBOutlet weak var table: UITableView!
- @IBOutlet weak var userTextInput: UITextField!
- @IBOutlet weak var locateMeButton: UIButton!
- @IBOutlet weak var submitUserInputButton: UIButton!
- @IBOutlet weak var typeOfLocatingMethod: UISegmentedControl!
- let locationManager:CLLocationManager = CLLocationManager()
- let googleAPIUrl:String = "https://maps.googleapis.com/maps/api/place/nearbysearch/json"
- let APIKey:String = "AIzaSyBpMA5wLvKdtSl0Cv76VmxoYvvRn6mLCn4"
- let radius:Int = 500
- var wasDataFetched:Bool = false
- let session = URLSession.shared
- var userLat:Double = 0
- var userLong:Double = 0
- let decoder = JSONDecoder()
- var hospitals = [Hospital]()
- override func viewDidLoad() {
- super.viewDidLoad()
- toggleUIElements(status: false)
- locationManager.delegate = self
- table.isHidden = true
- table.dataSource = self
- table.delegate = self
- table.reloadData()
- }
- @IBAction func locateMeButtonPressed(_ sender: Any) {
- locationManager.requestWhenInUseAuthorization()
- locationManager.startUpdatingLocation()
- locationManager.distanceFilter = 100
- }
- func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
- for currentLocation in locations {
- userLat = currentLocation.coordinate.latitude
- userLong = currentLocation.coordinate.longitude
- fetchNearbyPlacesData(long: userLong, lat: userLat)
- }
- }
- func fetchNearbyPlacesData(long: Double, lat: Double) {
- if(!wasDataFetched) {
- let URLLocation = "\(googleAPIUrl)?location=\(lat),\(long)"
- let URLRadius = "\(URLLocation)&radius=\(radius)"
- let URLType = "\(URLRadius)&types=hospital"
- let finalURL:String = "\(URLType)&key=\(APIKey)"
- guard let url = URL(string: finalURL) else {return}
- let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
- guard let dataResponse = data,
- error == nil else {
- print(error?.localizedDescription ?? "Response Error")
- return }
- do{
- let jsonResponse = try JSONSerialization.jsonObject(with:
- dataResponse, options: []) as! [String: Any]
- if let results = jsonResponse["results"] as? [[String: AnyObject]] {
- for result in results {
- var name:String = ""
- var address:String = ""
- var distance:Double = 0.0
- var long:Double = 0.0
- var lat:Double = 0.0
- var tags:[String] = []
- name = result["name"]! as! String
- if let vicinity = result["vicinity"] {
- address = vicinity as! String
- }
- if let types = result["types"] as? [String] {
- tags = types
- }
- if let geometry = result["geometry"] as? [String: AnyObject] {
- if let location = geometry["location"] as? [String: AnyObject] {
- long = location["lng"]! as! Double
- lat = location["lat"]! as! Double
- distance = self.calculateDistance(long1: location["lng"]! as! Double, lat1: location["lat"]! as! Double, long2: self.userLong, lat2: self.userLat)
- }
- }
- self.hospitals.append(Hospital(lat: lat, long: long, name: name, distance: distance, address: address, tags: tags))
- }
- self.hospitals.sort { (hos1, hos2) in
- return hos1.distance < hos2.distance
- }
- print(self.hospitals.count)
- self.table.isHidden = false
- DispatchQueue.main.async {
- self.table.isHidden = false
- self.table.reloadData()
- }
- //myArr.sort { (lhs, rhs) in return lhs.deadline < rhs.deadline }
- for hospital in self.hospitals {
- print(hospital)
- }
- }
- } catch let parsingError {
- print("Error", parsingError)
- }
- }
- task.resume()
- }
- }
- func calculateDistance(long1: Double, lat1: Double, long2: Double, lat2: Double) -> Double {
- let R:Float = 6371e3
- let radLat1 = deg2rad(lat1)
- let radLat2 = deg2rad(lat2)
- let phi = deg2rad(lat2-lat1)
- let lambda = deg2rad(long1-long2)
- let a = sin(phi/2) * sin(phi/2) + cos(radLat1) * cos(radLat2) * sin(lambda/2) * sin(lambda/2)
- let c = 2 * atan2(sqrt(a), sqrt(1-a))
- let d:Float = R * Float(c)
- return Double(d)
- }
- func deg2rad(_ number: Double) -> Double {
- return number * .pi / 180
- }
- func toggleUIElements(status: Bool) {
- locateMeButton.isHidden = status
- userTextInput.isHidden = !status
- submitUserInputButton.isHidden = !status
- }
- @IBAction func locatingMethodChange(_ sender: Any) {
- switch typeOfLocatingMethod.selectedSegmentIndex
- {
- case 0:
- toggleUIElements(status: false)
- case 1:
- toggleUIElements(status: true)
- default:
- toggleUIElements(status: false)
- }
- }
- func numberOfSectionsInTableView(tableView: UITableView) -> Int {
- return 1
- }
- func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
- print("SELF", self.hospitals.count)
- print("NIE SELF", self.hospitals.count)
- return self.hospitals.count
- }
- func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
- print("WYWOLALEM SIE XD")
- let myCell = tableView.dequeueReusableCell(withIdentifier: "hospitalTableCell", for: indexPath) as! HospitalTableCell
- let item = self.hospitals[indexPath.item]
- myCell.cellAddress.text = item.address
- myCell.cellTitle.text = item.name
- myCell.cellTags.text = item.tags.joined(separator: ", ")
- myCell.cellDistance.text = String(round(item.distance)) + " m"
- print(item)
- return myCell
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement