Search code examples
iosswiftmkmapviewmapkitmkpointannotation

How to make remove a map pin after a certain amount of time has passed using Swift?


I have a pin on a map that I would like to be removed after a certain amount of time has passed. I have implemented all proper protocols to place the annotation. Just not sure where to have something that checks if the value for the time variable is >= a certain amount.

var timer = NSTimer()

let annotation = MKPointAnnotation()

var time = 0

//button press creates a pin

@IBAction func buttonPressed(sender: AnyObject) {

        func timerFunc() {

            time++

        }

        annotation.coordinate = location

        annotation.title = "Place"

        annotation.subtitle = "Description"

        map.addAnnotation(annotation)

            timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("timerFunc"), userInfo: nil, repeats: true)

        }

        if time >= 5 {
            timer.invalidate()
        } 

    }

Now it seems I would need to place something like this somewhere:

if time >= 5 {
    map.removeAnnotation(annotation)
  }

Solution

  • You can use NSTimer to call a method which removes annotation.

    var myTimer: NSTimer!
    
    
    @IBAction func buttonPressed(sender: AnyObject) {
    
        annotation.coordinate = location
        annotation.title = "Place"
        annotation.subtitle = "Description"
        map.addAnnotation(annotation)
        myTimer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "runTimedCode", userInfo: nil, repeats: false)
        }
    }
    
    //this method will be called after 5 seconds
    func runTimedCode() {  
           map.removeAnnotation(annotation)
    }