我在代码中添加了MapView,MKUserTrackingButton按钮,localManager,DispatchGroup:
let mapView: MKMapView = {
let mapView = MKMapView()
mapView.translatesAutoresizingMaskIntoConstraints = false
return mapView
}()
private var userTrackingButton: MKUserTrackingButton!
private let locationManager = CLLocationManager()
let myGroup = DispatchGroup()
var array = [Car]()
在ViewDidLoad中,我设置了:
myGroup.enter()
从Firebase获取数据:
observeCars()
等待,直到我从Firebase中获取所有数据:
myGroup.notify(queue: DispatchQueue.main) {
self.view.addSubview(self.mapView)
//Here code to set the mapView in the view
self.setupUserTrackingButton()
self.locationManager.delegate = self
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
}
在这里,我在视图中设置按钮:
private func setupUserTrackingButton() {
mapView.showsUserLocation = true
userTrackingButton = MKUserTrackingButton(mapView: mapView)
userTrackingButton.layer.backgroundColor = UIColor(white: 0.5, alpha: 1).cgColor
userTrackingButton.layer.borderColor = UIColor.white.cgColor
userTrackingButton.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(userTrackingButton)
///Code to set in the view the button
}
我设置与Firebase的连接以获取数据的类:
class APIService: NSObject {
class func observeCars(completion: ((_ car: Car) -> Void)?) {
let ref = Database.database().reference()
ref.child("Cars").observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: Any] {
let car = Car(dictionary: dictionary)
completion?(car)
}
}, withCancel: nil)
}
}
这是函数(用MainViewController编写),我从Firebase中获取数据并将其添加到数组中:
internal func observeCars() {
/////I think this is the part that makes It doesn't appear because
if I delete this part, it works like I aspect
APIService.observeCars {
(car) in
self.array.append(car)
print(self.array.count)
if self.array.count == totalCars {
self.myGroup.leave()
}
}
//////////
}
有任何提示吗?谢谢
答案 0 :(得分:0)
我在mapView中添加了MKUserTrackingButton:
mapView.addSubview(userLocationButton)
对我有用。