user154248 user154248 - 4 months ago 8
Swift Question

How To Get How Long Ago An Annotation Was Placed iOS

So I am working with the

iOS Mapkit
, and part of the application requires me to show long ago an annotation was placed when somebody taps on it. So far I've tried this:

//MARK: Report Date And Time Details
let ReportTime = NSDate()
let TimeStamp = NSDateFormatter()
TimeStamp.timeStyle = NSDateFormatterStyle.ShortStyle
TimeStamp.dateStyle = NSDateFormatterStyle.ShortStyle
TimeStamp.stringFromDate(ReportTime)


And then set the description of the annotation to
Report Time
. Instead of doing this, I would like for the annotation to say "53,54,55 Minutes Ago etc." Is there a simple way to accomplish this?

Thanks All!

Rob Rob
Answer

Two things:

  1. To get the time elapsed, I'd suggest using a NSDateComponentsFormatter:

    let formatter = NSDateComponentsFormatter()
    formatter.allowedUnits = [.Hour, .Minute]
    formatter.unitsStyle = .Full
    
    let string = formatter.stringFromDate(date1, toDate: date2)
    

    That generates a string that looks like:

    2 hours, 1 minute

  2. If you just want the callout to show you the elapsed time, the easiest way is to define a custom annotation with a computed property for title (or subtitle, whichever you prefer). For example:

    class CustomAnnotation: NSObject, MKAnnotation {
        let startDate = NSDate()
        var coordinate: CLLocationCoordinate2D
        var subtitle: String?
    
        init(coordinate: CLLocationCoordinate2D) {
            self.coordinate = coordinate
            super.init()
        }
    
        var title: String? {
            let formatter = NSDateComponentsFormatter()
            formatter.allowedUnits = [.Hour, .Minute]
            formatter.unitsStyle = .Full
    
            let elapsedString = formatter.stringFromDate(startDate, toDate: NSDate())!
    
            return "Added \(elapsedString) ago"
        }
    }
    

    Then, when the annotation view needs to present the standard callout, it retrieve the title, which will be dynamically computed with the elapsed time.

Clearly, you can change this as you see fit (e.g. is startDate really just when you created the annotation, or is it some stored property that you can set from your data source; you can change the initializer to pass additional properties; etc.), but this illustrates the basic idea.

enter image description here

Comments