Как получить маркеры местоположения из базы данных Firebase в реальном времени и добавить к представлению карты в Xcode с помощью swift - PullRequest
0 голосов
/ 18 июня 2019

Поэтому я пытаюсь заменить жестко закодированную версию данных массива загрузкой из базы данных Firebase в реальном времени, и я хочу сохранить эту загрузку в 4 отдельных массива или 1 массив другого массива на ночной клуб

база данных FireBase в реальном времени. Структура json

enter image description here

Я не очень старался, так как я новичок в Firebase, поэтому я не знаю, какая помощь будеточень признателен

// ViewControllerThree.swift
import Foundation
import UIKit
import MapKit
import CoreLocation
import FirebaseDatabase

class ViewControllerThree: UIViewController, CLLocationManagerDelegate, UITableViewDataSource, UITableViewDelegate { // new last 2

@IBOutlet weak var clubInfo: UIView!
@IBOutlet weak var mapView: MKMapView!

@IBOutlet weak var miniTableView: UITableView! // new

var locationManager = CLLocationManager()
var artworks: [Artwork] = []

var nightClubs = [NightClubs]() // new new

override func viewDidLoad() {
    super.viewDidLoad()
    miniTableView.dataSource = self
    miniTableView.delegate = self

    //dataService()
    DataService.ds.REF_BARS.observeSingleEvent(of: .value, with: { (snapshot) in
        print(snapshot.value as Any)
        if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
            for snap in snapshot {
                print(snap)
                if let barData = snap.value as? Dictionary<String, AnyObject> {
                    let bar = NightClubs(barData: barData)
                    self.nightClubs.append(bar)
                    print(self.nightClubs)
                    self.miniTableView.reloadData()
                }
                self.miniTableView.reloadData()
            }
            self.miniTableView.reloadData()
        }
        self.miniTableView.reloadData()
    })
    clubInfo.layer.cornerRadius = 4

    self.locationManager.requestAlwaysAuthorization()
    self.locationManager.requestWhenInUseAuthorization()

    if CLLocationManager.locationServicesEnabled() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
        mapView.showsUserLocation = true
    } else {
        print("Location service disabled, Give permission or connect to the internet");
    }

    mapView.delegate = self
    let artwork = Artwork(title: "Alley",
                          locationName: "Barrie",
                          discipline: "Night Club",
                          coordinate: CLLocationCoordinate2D(latitude: 44.3894, longitude: -79.6889)
                         )
    mapView.addAnnotation(artwork)
    mapView.register(ArtworkView.self,
                     forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
    getLocations()
    getTitleList()
    titleMaker()
    //pullLocations()
}

public func dataService() {
    DataService.ds.REF_BARS.observeSingleEvent(of: .value, with: { (snapshot) in
        print(snapshot.value as Any)
        if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
            for snap in snapshot {
                print(snap)
                if let barData = snap.value as? Dictionary<String, AnyObject> {
                    let bar = NightClubs(barData: barData)
                    self.nightClubs.append(bar)
                    print(self.nightClubs)
                    self.miniTableView.reloadData()
                }
                self.miniTableView.reloadData()
            }
            self.miniTableView.reloadData()
        }
        self.miniTableView.reloadData()
    })
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return nightClubs.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "countCell") as! countCell
    //let barz = nightClubs[indexPath.row]
    let nightClub: NightClubs

    nightClub = nightClubs[indexPath.row]

    cell.goingCountLabel.text = nightClub.goingCount
    cell.liveCountLabel.text = nightClub.liveCount
    return cell
}

let regionRadius: CLLocationDistance = 1000

func centerMapOnLocation(location: CLLocation) {
    let coordinateRegion = MKCoordinateRegion.init(center: location.coordinate,
        latitudinalMeters: regionRadius, longitudinalMeters: regionRadius)
    mapView.setRegion(coordinateRegion, animated: true)
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userLocation:CLLocation = locations[0] as CLLocation
    manager.stopUpdatingLocation()
    let coordinations = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude,longitude: userLocation.coordinate.longitude)
    let span = MKCoordinateSpan.init(latitudeDelta: 0.1,longitudeDelta: 0.1)
    let region = MKCoordinateRegion(center: coordinations, span: span)
    mapView.setRegion(region, animated: true)
}

var titleArray = [String]()
var locationNameArray = [String]()
var disciplineArray = [String]()
var coordinateArray = [CLLocationCoordinate2D]()
static var titleArraytwo = [String]()

public func titleMaker(){
    ViewControllerThree.titleArraytwo = titleArray
}

public func pullLocations() {
    let nightClub: NightClubs

    titleArray.append(nightClub.name) // to add all nightClub.name to this array
    locationNameArray.append("locationName") // to add all nightClub.location to this array
    disciplineArray.append("type") // to add all nightClub.type to this array
    coordinateArray.append(CLLocationCoordinate2D(latitude: 0, longitude: 0)) // to add all nightClub.latitude and nightClub.longitude to this array
}

public func getLocations() {

    titleArray.append("Alley")
    titleArray.append("Donaleigh's Irish Public House")
    titleArray.append("Queens")
    titleArray.append("The Ranch")
    titleArray.append("Rebel")
    titleArray.append("Moda")
    titleArray.append("Fiction")
    titleArray.append("Partytown")
    titleArray.append("Avenue")
    titleArray.append("Aria")
    titleArray.append("Lavish")
    titleArray.append("TABU")
    titleArray.append("Trappers Alley")
    titleArray.append("Phil's Grandsons Place")
    titleArray.append("Dallas")
    titleArray.append("The Pub On King")
    titleArray.append("Prohibition")
    titleArray.append("Yuk yuks Comedy club")
  // titleArraytwo = titleArray

    locationNameArray.append("Barrie")
    locationNameArray.append("Barrie")
    locationNameArray.append("Barrie")
    locationNameArray.append("Barrie")
    locationNameArray.append("Toronto")
    locationNameArray.append("North York") //
    locationNameArray.append("Toronto")
    locationNameArray.append("Guelph")
    locationNameArray.append("Vaughn")
    locationNameArray.append("Peterborough")
    locationNameArray.append("London")//
    locationNameArray.append("Guelph")
    locationNameArray.append("Guelph")
    locationNameArray.append("Waterloo")
    locationNameArray.append("kitchener")
    locationNameArray.append("waterloo") //
    locationNameArray.append("London")
    locationNameArray.append("London")

    disciplineArray.append("Night Club")    // Alley
    disciplineArray.append("Bar")           // donaleighs
    disciplineArray.append("Night Club")    // queens
    disciplineArray.append("Night Club")    // ranch
    disciplineArray.append("Night Club")    // rebel
    disciplineArray.append("Night Club")    // moda
    disciplineArray.append("Night Club")    // Fiction 180 Pearl Street, Toronto, ON, M5J1J2
    disciplineArray.append("Night Club")    // party town nightclub 100 carden st
    disciplineArray.append("Night Club")    // Avenue Night Club 2800 Hwy 7 W, Concord, ON L4K 1W8
    disciplineArray.append("Night Club")    // ARIA club 331 George Street North, Peterborough, ON K9H 3P9
    disciplineArray.append("Night Club")    // LAVISH club 238 Dundas St, London, ON N6A 1H3
    disciplineArray.append("Night Club")    // TABU nightclub 96 macdonell st, guelph N1H4e5
    disciplineArray.append("Night Club")    // Trappers Alley night club
    disciplineArray.append("Night Club")    // Phil's Grandson's Place
    disciplineArray.append("Night Club")    // Dallas
    disciplineArray.append("Bar")           // the pub on king
    disciplineArray.append("Night Club")    // prohibition
    disciplineArray.append("Bar")           // Yuk yuks comedy club // prime money

    coordinateArray.append(CLLocationCoordinate2D(latitude: 44.3894, longitude: -79.6889)) // johnson's
    coordinateArray.append(CLLocationCoordinate2D(latitude: 44.3894, longitude: -79.6891)) // donaleighs
    coordinateArray.append(CLLocationCoordinate2D(latitude: 44.3895, longitude: -79.6868)) // queens
    coordinateArray.append(CLLocationCoordinate2D(latitude: 44.3903, longitude: -79.6915)) // ranch
    coordinateArray.append(CLLocationCoordinate2D(latitude: 43.6410, longitude: -79.3547)) // rebel
    coordinateArray.append(CLLocationCoordinate2D(latitude: 43.7761, longitude: -79.4935)) // moda
    coordinateArray.append(CLLocationCoordinate2D(latitude: 43.6476, longitude: -79.3891)) // fiction
    coordinateArray.append(CLLocationCoordinate2D(latitude: 43.5451, longitude: -80.2468)) // partytown
    coordinateArray.append(CLLocationCoordinate2D(latitude: 43.7962, longitude: -79.5190)) // avenue
    coordinateArray.append(CLLocationCoordinate2D(latitude: 44.3038, longitude: -78.3201)) // aria
    coordinateArray.append(CLLocationCoordinate2D(latitude: 42.9847, longitude: -81.2468)) // LAVISH Nightclub
    coordinateArray.append(CLLocationCoordinate2D(latitude: 43.5451, longitude: -80.2470)) // tabu
    coordinateArray.append(CLLocationCoordinate2D(latitude: 43.5452, longitude: -80.2469)) // trappers alley
    coordinateArray.append(CLLocationCoordinate2D(latitude: 43.4752, longitude: -80.5244)) // phil grandson place
    coordinateArray.append(CLLocationCoordinate2D(latitude: 43.4520, longitude: -80.4950)) // dallas
    coordinateArray.append(CLLocationCoordinate2D(latitude: 43.4678, longitude: -80.5232)) // pub on king
    coordinateArray.append(CLLocationCoordinate2D(latitude: 42.9841, longitude: -81.2505)) // prohib
    coordinateArray.append(CLLocationCoordinate2D(latitude: 42.9896, longitude: -81.2192)) // yuk yuk
}

    public func getTitleList(){
        // var titles = titleArray // fix code
        var names = locationNameArray
        var type  = disciplineArray
        var coords = coordinateArray

        while 0 < titleArray.count {
          let location = Artwork(title: titleArray.remove(at: 0),
                                 locationName: names.remove(at: 0),
                                 discipline: type.remove(at: 0),
                                 coordinate: coords.remove(at: 0))
            mapView.addAnnotation(location)
        }
    }
}

Я пытаюсь заменить func getLocations() на func pullLocations(), так как это спасет меня на 100 строк и сделает его динамичным

1 Ответ

0 голосов
/ 19 июня 2019

Вы можете просто заменить свой старый метод tableView forRowAt на

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "countCell") as! countCell
    let nightClub: NightClubs
    nightClub = nightClubs[indexPath.row]

    let artwork = Artwork(title: nightClub.name,
                          locationName: nightClub.location,
                          discipline: nightClub.type,
                          coordinate: CLLocationCoordinate2D(latitude: Double(nightClub.latitude)!, longitude: Double(nightClub.longitude)!)
    )
    mapView.addAnnotation(artwork)
    cell.goingCountLabel.text = nightClub.goingCount
    cell.liveCountLabel.text = nightClub.liveCount
    return cell
}

затем удалите жестко закодированные объекты Artwork и их отношения

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...