无法从for循环内返回值?迅速

时间:2018-08-08 21:55:54

标签: ios swift loops firebase mkmapview

我正在努力使用一个函数来获取选定的注释(didSelect视图:),对照数据库中的所有注释坐标检查坐标,并返回匹配注释的uid。

但是,我认为我的for循环出错了,因为它没有返回在didSelect函数中使用的值。在didSelect view:中调用searchForEvent函数,并根据数据库检查所选注释的经度和纬度。

此处提供代码:

 func searchForEvent(latitude: CLLocationDegrees, longitude: CLLocationDegrees) -> String? {
    var eventCoordinate: CLLocationCoordinate2D?
    var eventKey: String?
    var selectedEventKey = ""
    DataService.instance.REF_EVENTS.observeSingleEvent(of: .value, with: { (snapshot) in
        print("1")
        if let eventSnapshot = snapshot.children.allObjects as? [DataSnapshot] {
            for event in eventSnapshot {
                eventKey = event.key
                print("\(eventKey)")
                print("2")
                if event.childSnapshot(forPath: "coordinate").value != nil  {
                    if let eventDict = event.value as? Dictionary<String, AnyObject> {
                        print("3")
                        //pull out value of key coordinate
                        let coordinateArray = eventDict["coordinate"] as! NSArray
                        print(coordinateArray)
                        eventCoordinate = CLLocationCoordinate2D(latitude: coordinateArray[0] as! CLLocationDegrees, longitude: coordinateArray[1] as! CLLocationDegrees)
                        print(eventCoordinate)
                        if (eventCoordinate?.latitude, eventCoordinate?.longitude) == (latitude, longitude) {
                            selectedEventKey = eventKey!
                            print("\(selectedEventKey), correct event")
                        } else {
                            print("incorrect event")
                        }
                    }
                }
            }
        }
    })
    return selectedEventKey

//        if selectedEventKey != nil {
//            print("4")
//            print("\(selectedEventKey)")
//            return selectedEventKey
//        } else {
//            print("empty key")
//            return nil
//        }
    }

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    print("selected")
    self.selectedAnnotation = view.annotation
    print(selectedAnnotation?.coordinate.latitude as Any)
    print(selectedAnnotation?.coordinate.longitude as Any)
    let lat = selectedAnnotation?.coordinate.latitude
    let lon = selectedAnnotation?.coordinate.longitude

    selectedAnnotationKey = searchForEvent(latitude: lat!, longitude: lon!)

    if selectedAnnotationKey == nil {
        print("no key")
    } else {
        print("found event final! \(selectedAnnotationKey)")
    }
}

在didSelect函数中selectedAnnotationKey始终为nil:(

非常感谢您的帮助!

编辑

这是更新的功能,非常感谢Sh_Khan的帮助。在调试区域中打印正确的值时,它将继续循环遍历数据库中的“事件”,并在完成后最后返回nil。

func searchForEvent(latitude: CLLocationDegrees, longitude: CLLocationDegrees , completion:@escaping(_ str:String?) -> Void ) {
    var eventCoordinate: CLLocationCoordinate2D?
    var eventKey: String?
    var selectedEventKey = ""
    DataService.instance.REF_EVENTS.observeSingleEvent(of: .value, with: { (snapshot) in
        print("1")
        if let eventSnapshot = snapshot.children.allObjects as? [DataSnapshot] {
            for event in eventSnapshot {
                eventKey = event.key
                print("\(eventKey)")
                print("2")
                if event.childSnapshot(forPath: "coordinate").value != nil  {
                    if let eventDict = event.value as? Dictionary<String, AnyObject> {
                        print("3")
                        //pull out value of key coordinate
                        let coordinateArray = eventDict["coordinate"] as! NSArray
                        print(coordinateArray)
                        eventCoordinate = CLLocationCoordinate2D(latitude: coordinateArray[0] as! CLLocationDegrees, longitude: coordinateArray[1] as! CLLocationDegrees)
                        print(eventCoordinate)
                        if (eventCoordinate?.latitude, eventCoordinate?.longitude) == (latitude, longitude) {
                            selectedEventKey = eventKey!
                            print("\(selectedEventKey), correct event")
                            completion(selectedEventKey)
                        } else {
                            print("incorrect event")
                            completion(nil)
                        }
                    }
                }
            }
        }
    })
}


func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    print("selected")
    self.selectedAnnotation = view.annotation
    let lat = selectedAnnotation?.coordinate.latitude
    let lon = selectedAnnotation?.coordinate.longitude

    searchForEvent(latitude: lat!, longitude: lon!) { (str) in
        self.selectedAnnotationKey = str
        print("here it is \(str)")

        print(self.selectedAnnotationKey)
    }
}

和调试打印输出:

selected
1
Optional("31E2932B-A037-4BB1-B93E-7504B61AC4E7")
2
3
(
    "-36.84745654404946",
    "174.7760903030886"
)
Optional(__C.CLLocationCoordinate2D(latitude: -36.847456544049464, longitude: 174.77609030308864))
incorrect event
here it is nil
nil
Optional("71173419-7E08-415C-9236-B1C8495A6BA9")
2
3
(
    "-36.86687593953122",
    "174.7585811441448"
)
Optional(__C.CLLocationCoordinate2D(latitude: -36.866875939531219, longitude: 174.75858114414478))

下面找到正确的事件,str和self.selectedAnnotationKey都是正确的,但是继续进行下去并覆盖它!

71173419-7E08-415C-9236-B1C8495A6BA9, correct event
here it is Optional("71173419-7E08-415C-9236-B1C8495A6BA9")
Optional("71173419-7E08-415C-9236-B1C8495A6BA9")
Optional("7AC6429E-74B6-4A4E-A638-53981ACBFFBA")
2
3
(
    "-36.2429468",
    "175.3981152"
)
Optional(__C.CLLocationCoordinate2D(latitude: -36.242946799999999, longitude: 175.39811520000001))
incorrect event
here it is nil
nil

2 个答案:

答案 0 :(得分:2)

您需要完成

 func searchForEvent(latitude: CLLocationDegrees, longitude: CLLocationDegrees , completion:@escaping(_ str:String?) -> Void ) {
    var eventCoordinate: CLLocationCoordinate2D?
    var eventKey: String?
    var selectedEventKey = ""
    DataService.instance.REF_EVENTS.observeSingleEvent(of: .value, with: { (snapshot) in
        print("1")
        if let eventSnapshot = snapshot.children.allObjects as? [DataSnapshot] {
            for event in eventSnapshot {
                eventKey = event.key
                print("\(eventKey)")
                print("2")
                if event.childSnapshot(forPath: "coordinate").value != nil  {
                    if let eventDict = event.value as? Dictionary<String, AnyObject> {
                        print("3")
                        //pull out value of key coordinate
                        let coordinateArray = eventDict["coordinate"] as! NSArray
                        print(coordinateArray)
                        eventCoordinate = CLLocationCoordinate2D(latitude: coordinateArray[0] as! CLLocationDegrees, longitude: coordinateArray[1] as! CLLocationDegrees)
                        print(eventCoordinate)
                        if (eventCoordinate?.latitude, eventCoordinate?.longitude) == (latitude, longitude) {
                            selectedEventKey = eventKey!
                            print("\(selectedEventKey), correct event")
                            completion(selectedEventKey)
                        } else {
                            print("incorrect event")
                            completion(nil)
                        }
                    }
                }
            }
        }
    })
 }

//

打电话

searchForEvent(//value1,//value2) { (str) in
  print(str)
}

答案 1 :(得分:1)

您需要一个完成处理程序