Firebase数据和意外的零

时间:2019-10-10 16:40:34

标签: swift firebase firebase-realtime-database

我的最终目标是在MapKit的地图上显示注释。但是,无法从Firebase加载数据。 这是代码:

var hotels = [Hotel]()

override func viewDidLoad() {
    super.viewDidLoad()
    map.delegate = self
    checkLocationServices()
    observe()
}

函数观察如下:

func observe() {
        Data().getAllHotel { (hotelA) -> (Void) in
            if let hotel = hotelA {
                print("hotel: ", hotel)
                self.hotels.append(hotel)
                let hotelAnnotation = MKPointAnnotation()
                hotelAnnotation.title = "\(hotel.hotelName)"
                hotelAnnotation.coordinate = CLLocationCoordinate2D(latitude: hotel.latitude, longitude: hotel.longitude)
                self.map.addAnnotation(hotelAnnotation)
            }
        }
}

请注意,if语句中的打印不为空。 但是,行hotelAnnotation.title导致错误意外出现nil,我不明白为什么。

此外,这是Data类中的getAllHotel函数:

func getAllHotel(closure: HotelClosure?) {
        let ref = Ref().databaseHotels
        ref.observe(.childAdded) { (snapshot) in
            if let dict = snapshot.value as? Dictionary<String, AnyObject> {
                let hotel = self.fromDictToHotel(key: snapshot.key, dict: dict)
                closure?(hotel)
            } else {
                closure?(nil)
            }
        }
    }

    func fromDictToHotel(key: String, dict: Dictionary<String, AnyObject>) -> Hotel? {
        guard let hotelName = dict["name"] as? String else { return nil }
        guard let latitude = dict["latitude"] as? Double else { return nil }
        guard let longitude = dict["longitude"] as? Double else { return nil }
        let hotelDescription = dict["description"] as? String
        let hotelGrade = dict["grade"] as? Double
        let hotelImageUrl = dict["hotelImageUrl"] as? String

        let hotel = Hotel(hid: key, hotelName: hotelName, hotelDescription: hotelDescription, latitude: latitude, longitude: longitude, grade: hotelGrade, url: hotelImageUrl)
        return hotel
    }

在此先感谢您的帮助!

0 个答案:

没有答案