Массив CLLocationCoordinate2D, заполненный из Firebase, не сохраняет свои записи.Swift 4 - PullRequest
0 голосов
/ 05 декабря 2018

У меня проблема с alertNotificationCoordinatesArray, в которой хранится CLLocationCoordinates2D from retrieving posts from Firebase. Oddly the array gets populated every time I enter NewMapViewController . I thought that it would stay populated and only get new entries as the child observer send a new post from Firebase, but instead it's retrieving the posts every time NewMapViewController loads. My problem is, that I get to NewMapViewController eighter from a menu or from a notification action button. In the second case I use alertNotificationCoordinatesArray in the checkAlerts2`функция, поэтому мне нужно, чтобы она уже была заполнена, но она пуста.

вот интересующая часть кода:

    override func viewDidLoad() {
        super.viewDidLoad()


        mapView.delegate = self
        locationManager.delegate = self
//        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
        locationManager.distanceFilter = kCLDistanceFilterNone
        locationManager.allowsBackgroundLocationUpdates = true  //for getting user location in background mode as well

        mapView.showsUserLocation = true
        mapView.userTrackingMode = .follow   //map following user


//        let globalLocationManager: GlobalLocationManager
        configureLocationServices()
        addDoubleTap() // enabling duble tap gesture recognizer
//        mapView.isUserInteractionEnabled = true


        let location = locationManager.location?.coordinate

        if location == nil {
            return
        }

        let region = MKCoordinateRegionMakeWithDistance(location!, 1000, 1000) // set mapView based on user location coordinates
        mapView.setRegion(region, animated: true)
        centerMapOnLocation()

        // alerts coordinates to post to Firebase
//        let alertDrawLatitude =  alertDrawCoordinates?.latitude    // not used ?
//        let alertDrawLomgitude = alertDrawCoordinates?.longitude   // not used ?
//        let title: String? = alertNotificationType                 // not used ?
//        var subtitle: String? = alertNotificationType              // not used ?

        //  user alert notification. takes coordinates from alertNotificationArray( populated with firebase returning coordinate for all alerts

         displayAlerts()

        print("alertNotificationCoordinatesArray at loading NewMapViewController is\(alertNotificationCoordinatesArray)")

        // if coming from alert notification
        if NewMapViewController.checkCounter > 0 {
            checkAlerts2()
        } else { return }


    }

функция, которая использует сообщения Firebase:

func displayAlerts() { 

        ref = Database.database().reference()

        databaseHandle = ref?.child("Community").child("Alert Notifications").observe(.childAdded, with: { (snapshot) in

            //            defer { self.dummyFunctionToFoolFirebaseObservers() }
            guard let data = snapshot.value as? [String:String] else { return }
            guard let firebaseKey = snapshot.key as? String else { return }
            //                let date = data!["Date"]
            //                let time = data!["Time"]
            let dataLatitude = data["Latitude"]!
            let dataLongitude = data["Longitude"]!

            let type = data["Description"]!
            let id = Int(data["Id"]!)
            let doubledLatitude = Double(dataLatitude)
            let doubledLongitude = Double(dataLongitude)
            let recombinedCoordinate = CLLocationCoordinate2D(latitude: doubledLatitude!, longitude: doubledLongitude!)

            print("Firebase alerts posts retrieved")

//            print("Longitude Actual DataKey is \(String(describing: firebaseKey))")

//            print("fir long \((snapshot.value!, snapshot.key))")
            let userAlertAnnotation = UserAlert(type: type, coordinate: recombinedCoordinate, firebaseKey: firebaseKey, title: type,id: id!)
            self.userAlertNotificationArray.append(userAlertAnnotation)  // array of notifications coming from Firebase
            print("userAlertNotificationArray after retrieving from Firebase is : \(self.userAlertNotificationArray)")

            self.alertNotificationCoordinatesArray.append(recombinedCoordinate) // array for checkig alerts on route
             print("alertNotificationCoordinatesArray after retrieving from Firebase is : \(self.alertNotificationCoordinatesArray)")
            self.mapView.addAnnotation(userAlertAnnotation)

        })
    }

и распечатки с консоли:

alertNotificationCoordinatesArray at loading NewMapViewController is[]
Firebase alerts posts retrieved
userAlertNotificationArray after retrieving from Firebase is : [<fix_it_mapView.UserAlert: 0x1599f2e60>]
alertNotificationCoordinatesArray after retrieving from Firebase is : [__C.CLLocationCoordinate2D(latitude: 44.50139585197814, longitude: 11.335974854073397)]
CLLocationCoordinate2D(latitude: 44.50139585197814, longitude: 11.335974854073397)

Как я могу исправить этот массив, который очищается?

1 Ответ

0 голосов
/ 06 декабря 2018

Благодаря панике @guard, работающей по-другому, я вижу, что мой массив очищается каждый раз, когда я покидаю ВК, поэтому решения просто помещают его в структуру в отдельный файл swift.

import Foundation
import CoreLocation



struct MapArray {
    static var alertNotificationCoordinatesArray: [CLLocationCoordinate2D] = []  //  alert notification array coordinates only used to draw alerts on map and find route obstacles
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...