ios - 使用来自 Firebase 的数据在 map 上显示注释图像时出现奇怪的行为。环球银行金融电信协会4.1

标签 ios swift firebase mkannotation mkannotationview

奇怪的行为是,当我添加新注释时,无论是点击还是用户位置,它都会显示正确选择的图标。当 MapVC 第一次加载时,从 Firebase 检索到的帖子都具有相同的图标(最新发布的帖子的图标名称)。如果在发布新帖子后,我将 mapViewVc 退出到 menuVC 并重新进入 mapViewVC,则比每个图标再次显示相同的图标,现在是我之前发布的图标。 有几次,图标是随机选择的两个不同的图标。 我不明白为什么坐标是正确的,但图像却不是。

应用程序流程是: 我有一个mapView vc,我可以在屏幕上双击并通过按钮获取坐标或编码用户位置坐标,然后到达chooseIconVc,其中我有所有可用的图标可供选择用于注释。一旦我选择了一个,图标名称就会被传回到 unwindHere() 的 mapViewVC 中,它将图标名称存储到一个变量中,并将坐标存储到另一个变量中。在 postAlertNotification 中,这些变量被发布到 Firebase。 在 displayAlerts() 中,来自 Firebase 的数据被存储到变量中以初始化注释并添加到 mapView。

选择的图标:

@IBAction func unwindHere(sender:UIStoryboardSegue) { // data coming back
    if let sourceViewController = sender.source as? IconsViewController {
        alertNotificationType = sourceViewController.dataPassed
        if tapCounter > 0  {

            alertNotificationLatitude = String(describing: alertCoordinates.latitude)
            alertNotificationLongitude = String(describing: alertCoordinates.longitude)
            postAlertNotification()      // post new notification to Firebase

        } else {

            alertCoordinates = self.trackingCoordinates
            alertNotificationLatitude = String(describing: self.trackingCoordinates!.latitude)
            alertNotificationLongitude = String(describing: self.trackingCoordinates!.longitude)
            postAlertNotification()   // post new notification to Firebase

        }

    }
}

比帖子:

func postAlertNotification() {

        // to set next notification id as the position it will have in array ( because first position is 0 ) we use the array.count as value


        let latitude = alertNotificationLatitude
        let longitude = alertNotificationLongitude
        let alertType = alertNotificationType

        let post: [String:String] = [//"Date" : date as! String,
                                     //"Time" : time as! String,
                                     "Latitude" : latitude as! String,
                                     "Longitude" : longitude as! String,
                                     "Description" : alertType as! String]

        var ref: DatabaseReference!
        ref = Database.database().reference()
        ref.child("Community").child("Alert Notifications").childByAutoId().setValue(post)

    }

检索并显示:

    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"]!
            self.alertIconToDisplay = data["Description"]!

            let doubledLatitude = Double(dataLatitude)
            let doubledLongitude = Double(dataLongitude)
            let recombinedCoordinate = CLLocationCoordinate2D(latitude: doubledLatitude!, longitude: doubledLongitude!)

            print("Firebase post retrieved !")

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

            print("fir long \((snapshot.value!, snapshot.key))")
            self.userAlertAnnotation = UserAlert(type: self.alertIconToDisplay!, coordinate: recombinedCoordinate, firebaseKey: firebaseKey)
            self.mapView.addAnnotation(self.userAlertAnnotation)


        })
    }

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

        let annotationView = MKAnnotationView(annotation: userAlertAnnotation, reuseIdentifier: "")    //  CHANGE FOR NEW ANNOTATION : FULL DATA

        //added if statement for displaying user location blue dot
        if annotation is MKUserLocation{
            return nil
        } else {


            annotationView.image = UIImage(named: alertIconToDisplay!)                        //    choose the image to load

            let transform = CGAffineTransform(scaleX: 0.27, y: 0.27)
            annotationView.transform = transform
            return annotationView
        }
    }

变量声明:

var alertIconToDisplay: String?
var userAlertAnnotation: UserAlert!  
var alertNotificationType: String?                                             
var alertNotificationLatitude: String? 
var alertNotificationLongitude: String?  

更新:

注解类:

import MapKit


class UserAlert: NSObject , MKAnnotation {

    var type: String?

    var firebaseKey: String?

    var coordinate = CLLocationCoordinate2D()

    var image: UIImage?

    override init() {
    }
    init(type:String, coordinate:CLLocationCoordinate2D, firebaseKey: String) {

        self.type = type
        self.firebaseKey = firebaseKey

        self.coordinate = coordinate

    }
}

最佳答案

了解问题所在后,我被解释了如何将 displayAlert() 更改为

func displayAlerts() { // rajish version

        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 post retrieved !")

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

            print("fir long \((snapshot.value!, snapshot.key))")
            var userAlertAnnotation = UserAlert(type: type, coordinate: recombinedCoordinate, firebaseKey: firebaseKey, title: type,id: id!)
            self.userAlertNotificationArray.append(userAlertAnnotation)  // array of notifications coming from Firebase
            print("user alert array after append from Firebase is : \(self.userAlertNotificationArray)")
            self.alertNotificationArray.append(recombinedCoordinate) // array for checkig alerts on route
            self.mapView.addAnnotation(userAlertAnnotation)

        })

    }

和mapView:

func mapView(_ mapView: MKMapView, viewFor 注释: MKAnnotation) -> MKAnnotationView? {//拉吉什版本

    let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "")


    if annotation is MKUserLocation{
        return nil
    } else {

        print(annotation.coordinate)

        annotationView.image = UIImage(named:(annotationView.annotation?.title)! ?? "")

        //            annotationView.canShowCallout = true

        let transform = CGAffineTransform(scaleX: 0.27, y: 0.27)
        annotationView.transform = transform
        return annotationView
    }
}

解决了这个问题。

关于ios - 使用来自 Firebase 的数据在 map 上显示注释图像时出现奇怪的行为。环球银行金融电信协会4.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51756749/

相关文章:

objective-c - 非常奇怪的 ARC 内存泄漏

iOS UITableView : Empty header and footer height?

swift - 有没有办法以特定大小的批处理(比如 50)获取存储在 Realm 中的大量数据?

android - 程序类型已经存在 : com. google.android.gms.common.api.zzf

ios - 在 Delphi 中检测 iPad 方向

swift - AVAudioPlayer 即将为零

ios - 在 TableView 的自定义单元格上隐式展开可选值

javascript - Firebase 查询链?

javascript - Angular 中的 Firebase Auth 服务 - 数据不适用于所有 Controller

ios - 在数据库中进行一系列插入后内存不会减少