How to present a minutes countdown in a Live Activity?

I want my live activity to show "in 3 min" text, and for it to be updated automatically every minute. I saw I could do: Text(date, style: .relative) but sadly it include seconds too: 3 min, 2 sec. Is there a way for me to remove the seconds?

There are many examples for this use case in the "Design dynamic Live Activities" session from WWDC23, especially at 11:35. How are they implementing that?

Replies

Hey it took me days to figure it out, but the way is to use a custom date formatter. See example code below


import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Text(date, formatter: formatter)
        }
        .padding()
    }
    
    var date: Date {
        Date().addingTimeInterval(20*60)
    }
    
    var formatter: RelativeMinutesDateFormatter {
        RelativeMinutesDateFormatter()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

class RelativeMinutesDateFormatter : Formatter {
    
    open override func string(for obj: Any?) -> String? {
        guard let date = obj as? Date else {
            return nil
        }
        let minutes = Int(date.timeIntervalSince(.now) / 60)
        return "\(minutes)m"
    }
}
  • When I use a custom formatter, the date no longer live-updates—is this the same for you?

Add a Comment