Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 7.46 KB | None | 0 0
  1. //
  2. //  ViewController.swift
  3. //  Hospital
  4. //
  5. //  Created by Wojciech Miśta on 14/10/2019.
  6. //  Copyright © 2019 Wojciech Miśta. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10. import CoreLocation
  11. import Foundation
  12.  
  13. struct Hospital {
  14.     let lat: Double
  15.     let long: Double
  16.     let name: String
  17.     let distance: Double
  18.     let address: String
  19.     let tags: [String]
  20. }
  21.  
  22. class ViewController: UIViewController, CLLocationManagerDelegate, UITableViewDelegate, UITableViewDataSource {
  23.  
  24.     @IBOutlet weak var table: UITableView!
  25.     @IBOutlet weak var userTextInput: UITextField!
  26.     @IBOutlet weak var locateMeButton: UIButton!
  27.     @IBOutlet weak var submitUserInputButton: UIButton!
  28.     @IBOutlet weak var typeOfLocatingMethod: UISegmentedControl!
  29.     let locationManager:CLLocationManager = CLLocationManager()
  30.     let googleAPIUrl:String = "https://maps.googleapis.com/maps/api/place/nearbysearch/json"
  31.     let APIKey:String = "AIzaSyBpMA5wLvKdtSl0Cv76VmxoYvvRn6mLCn4"
  32.     let radius:Int = 500
  33.     var wasDataFetched:Bool = false
  34.     let session = URLSession.shared
  35.     var userLat:Double = 0
  36.     var userLong:Double = 0
  37.     let decoder = JSONDecoder()
  38.     var hospitals = [Hospital]()
  39.    
  40.    
  41.     override func viewDidLoad() {
  42.         super.viewDidLoad()
  43.         toggleUIElements(status: false)
  44.         locationManager.delegate = self
  45.         table.isHidden = true
  46.         table.dataSource = self
  47.         table.delegate = self
  48.         table.reloadData()
  49.     }
  50.    
  51.     @IBAction func locateMeButtonPressed(_ sender: Any) {
  52.         locationManager.requestWhenInUseAuthorization()
  53.         locationManager.startUpdatingLocation()
  54.         locationManager.distanceFilter = 100
  55.     }
  56.    
  57.     func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
  58.         for currentLocation in locations {
  59.             userLat = currentLocation.coordinate.latitude
  60.             userLong = currentLocation.coordinate.longitude
  61.             fetchNearbyPlacesData(long: userLong, lat: userLat)
  62.         }
  63.     }
  64.    
  65.     func fetchNearbyPlacesData(long: Double, lat: Double) {
  66.         if(!wasDataFetched) {
  67.             let URLLocation = "\(googleAPIUrl)?location=\(lat),\(long)"
  68.             let URLRadius = "\(URLLocation)&radius=\(radius)"
  69.             let URLType = "\(URLRadius)&types=hospital"
  70.             let finalURL:String = "\(URLType)&key=\(APIKey)"
  71.             guard let url = URL(string: finalURL) else {return}
  72.             let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
  73.             guard let dataResponse = data,
  74.                       error == nil else {
  75.                       print(error?.localizedDescription ?? "Response Error")
  76.                       return }
  77.                 do{
  78.                     let jsonResponse = try JSONSerialization.jsonObject(with:
  79.                         dataResponse, options: []) as! [String: Any]
  80.                    
  81.                     if let results = jsonResponse["results"] as? [[String: AnyObject]] {
  82.                         for result in results {
  83.                             var name:String = ""
  84.                             var address:String = ""
  85.                             var distance:Double = 0.0
  86.                             var long:Double = 0.0
  87.                             var lat:Double = 0.0
  88.                             var tags:[String] = []
  89.                            
  90.                             name = result["name"]! as! String
  91.                            
  92.                             if let vicinity = result["vicinity"] {
  93.                                 address = vicinity as! String
  94.                             }
  95.                            
  96.                             if let types = result["types"] as? [String] {
  97.                                 tags = types
  98.                             }
  99.                            
  100.                             if let geometry = result["geometry"] as? [String: AnyObject] {
  101.                                 if let location = geometry["location"] as? [String: AnyObject] {
  102.                                     long = location["lng"]! as! Double
  103.                                     lat = location["lat"]! as! Double
  104.                                     distance = self.calculateDistance(long1: location["lng"]! as! Double, lat1: location["lat"]! as! Double, long2: self.userLong, lat2: self.userLat)
  105.                                 }
  106.                             }
  107.                             self.hospitals.append(Hospital(lat: lat, long: long, name: name, distance: distance, address: address, tags: tags))
  108.                         }
  109.                         self.hospitals.sort { (hos1, hos2) in
  110.                             return hos1.distance < hos2.distance
  111.                         }
  112.                         print(self.hospitals.count)
  113.                         self.table.isHidden = false
  114.                         DispatchQueue.main.async {
  115.                             self.table.isHidden = false
  116.                             self.table.reloadData()
  117.                         }
  118.                         //myArr.sort { (lhs, rhs) in return lhs.deadline < rhs.deadline }
  119.  
  120.  
  121.                         for hospital in self.hospitals {
  122.                             print(hospital)
  123.                         }
  124.                     }
  125.                  } catch let parsingError {
  126.                     print("Error", parsingError)
  127.                }
  128.             }
  129.             task.resume()
  130.         }
  131.     }
  132.    
  133.     func calculateDistance(long1: Double, lat1: Double, long2: Double, lat2: Double) -> Double {
  134.         let R:Float = 6371e3
  135.         let radLat1 = deg2rad(lat1)
  136.         let radLat2 = deg2rad(lat2)
  137.         let phi = deg2rad(lat2-lat1)
  138.         let lambda = deg2rad(long1-long2)
  139.         let a = sin(phi/2) * sin(phi/2) + cos(radLat1) * cos(radLat2) * sin(lambda/2) * sin(lambda/2)
  140.         let c = 2 * atan2(sqrt(a), sqrt(1-a))
  141.         let d:Float = R * Float(c)
  142.         return Double(d)
  143.     }
  144.    
  145.     func deg2rad(_ number: Double) -> Double {
  146.         return number * .pi / 180
  147.     }
  148.    
  149.     func toggleUIElements(status: Bool) {
  150.         locateMeButton.isHidden = status
  151.         userTextInput.isHidden = !status
  152.         submitUserInputButton.isHidden = !status
  153.     }
  154.  
  155.     @IBAction func locatingMethodChange(_ sender: Any) {
  156.         switch typeOfLocatingMethod.selectedSegmentIndex
  157.         {
  158.         case 0:
  159.             toggleUIElements(status: false)
  160.         case 1:
  161.             toggleUIElements(status: true)
  162.         default:
  163.             toggleUIElements(status: false)
  164.         }
  165.     }
  166.    
  167.     func numberOfSectionsInTableView(tableView: UITableView) -> Int {
  168.         return 1
  169.     }
  170.     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  171.         print("SELF", self.hospitals.count)
  172.         print("NIE SELF", self.hospitals.count)
  173.         return self.hospitals.count
  174.      }
  175.  
  176.     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  177.          print("WYWOLALEM SIE XD")
  178.          let myCell = tableView.dequeueReusableCell(withIdentifier: "hospitalTableCell", for: indexPath) as! HospitalTableCell
  179.          let item = self.hospitals[indexPath.item]
  180.          myCell.cellAddress.text = item.address
  181.          myCell.cellTitle.text = item.name
  182.          myCell.cellTags.text =  item.tags.joined(separator: ", ")
  183.          myCell.cellDistance.text = String(round(item.distance)) + " m"
  184.          print(item)
  185.          return myCell
  186.      }
  187.  
  188.  
  189.    
  190. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement