cailixhill
cailixhill

Reputation: 45

Swift Mapbox custom user location annotation(Fatal Error)

I would like to create a custom user location pin which it gets the photoURL from Firebase and displays it. I tried using this Swift 3 - Mapbox - Customize User Location Annotation as a reference. However, I get an error when I build the custom class. I am not sure can I edit much in the MGLUserLocationAnnotationView but it seems like inherit UIView so I think it should be fine. Also, should I get the data from Firebase in the View Class or in the View Controller?

It is my custom class

class CustomUserLocationDisplayView: MGLUserLocationAnnotationView {

  var view: UIView!

  @IBOutlet weak var displayView: UIImageView!
  var imageView: UIImageView!

  required override init(reuseIdentifier: String?) {
    super.init(reuseIdentifier: reuseIdentifier)
    setup()
  }
  override init(frame: CGRect) {
    super.init(frame: frame)
  }
  required init?(coder aDecoder: NSCoder) {
    fatalError("Error")         <--------- I get this FATAL Error
  }

  func readFirebaseUserProfile(){
    let user = Auth.auth().currentUser
    let photoURL = user?.photoURL
      displayView.kf.setImage(with: photoURL)
  }

  func setup() {
    view = loadViewFromNib()
    displayView.layer.cornerRadius = 30
    addSubview(view)
  }

  func loadViewFromNib() -> UIView {
    let bundle = Bundle(for: type(of: self))
    let nib = UINib(nibName: "CustomUserLocationDisplayView", bundle: bundle)
    let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView

    return view
  }
}

It is my function for annotation

func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
    if annotation is MGLPointAnnotation{

    }else{
        var userLocationAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "user") as? CustomUserLocationDisplayView

        if userLocationAnnotationView == nil {
          userLocationAnnotationView = CustomUserLocationDisplayView(reuseIdentifier: reuseIdentifer)

        }

        return userLocationAnnotationView
      }
  }

Upvotes: 0

Views: 481

Answers (1)

jmkiley
jmkiley

Reputation: 976

One possible issue: I don't see where you call readFirebaseUserProfile. I would double check that it is being called.

Also, could you put a breakpoint after if userLocationAnnotationView == nil { and see if you are reaching it? You could also try something like:

 if annotation is MGLUserLocation && mapView.userLocation != nil {
    userLocationAnnotationView = CustomUserLocationDisplayView(reuseIdentifier: reuseIdentifer)

    return userLocationAnnotationView
 } else if annotation is MGLPointAnnotation {
    // Set annotations here
 }
 return nil

Upvotes: 1

Related Questions