top of page
  • Writer's pictureDon Peter

How to Implement Live Activities to display live data in Dynamic Island in iOS Apps


How to Implement Live Activities to display live data in Dynamic Island in iOS Apps

In today's fast-paced world, staying updated with the latest information is crucial. Whether it's live sports scores, breaking news, or real-time updates, having access to timely information can make a significant difference. That's where Live Activities in iOS come in.


With the ActivityKit framework, you can share live updates from your app directly on the Dynamic Island, allowing users to stay informed at a glance. Live Activities not only provide real-time updates but also offer interactive functionality. Users can tap on a Live Activity to launch your app and engage with its buttons and toggles, enabling them to perform specific actions without the need to open the app fully.


Additionally, on the Dynamic Island, users can touch and hold a Live Activity to reveal an expanded presentation with even more content.

Implementing Live Activities in your app is made easy with the ActivityKit framework. Live Activities utilize the power of WidgetKit and SwiftUI for their user interface, providing a seamless and intuitive experience for users. The ActivityKit framework handles the life cycle of each Live Activity, allowing you to initialize and update a Live Activity with its convenient API.

Defining ActivityAttributes


We start by defining the data displayed by your Live Activity through the implementation of ActivityAttributes. These attributes provide information about the static data that is presented in the Live Activity. Additionally, ActivityAttributes are used to specify the necessary custom Activity.ContentState type, which describes the dynamic data of your Live Activity.


import Foundation
import ActivityKit


struct FootballScoreAttributes: ActivityAttributes {
    public typealias GameStatus = ContentState


    public struct ContentState: Codable, Hashable {
        var score: String
        var time: Int
        ...
    }


    var venue: Int
}
    

Creating Widget Extension


To incorporate Live Activities into the widget extension, you can utilize WidgetKit. Once you have implemented the necessary code to define the data displayed in the Live Activity using the ActivityAttributes structure, you should proceed to add code that returns an ActivityConfiguration within your widget implementation.


import SwiftUI
import WidgetKit


@main
struct FootballScoreActivityWidget: Widget {
    var body: some WidgetConfiguration {
        ActivityConfiguration(for: FootballScoreAttributes.self) { context in

        } dynamicIsland: { context in
            // Create the presentations that appear in the Dynamic Island.
            // ...
        }
    }
}
    

If your application already provides widgets, you can incorporate the Live Activity by including it in your WidgetBundle. In case you don't have a WidgetBundle, such as when you offer only one widget, you should create a widget bundle following the instructions in the widget extension docs.



@main
struct FootballScoreWidgets: WidgetBundle {
    var body: some Widget {
        FootballScoreActivityWidget()
    }
}
    

Adding a Widget Interface


Here, football score widget utilizes standard SwiftUI views to provide compact and minimal presentations.


import SwiftUI
import WidgetKit


@main
struct FootballWidget: Widget {    
    var body: some WidgetConfiguration {
        ActivityConfiguration(for: FootballAttributes.self) { context in
          
        } dynamicIsland: { context in
            
            DynamicIsland {
            
            } compactLeading: {
                Label {
                    Text("Score \(context.attributes.score)")
                } icon: {
                    Image(systemName: "score")
                        .foregroundColor(.indigo)
                }
                .font(.caption2)
            } compactTrailing: {
                Text("Time \(context.state.time)")
                    .multilineTextAlignment(.center)
                    .frame(width: 40)
                    .font(.caption2)
            } minimal: {
                VStack(alignment: .center) {
                    Image(systemName: "time")
                    Text("Time \(context.state.time)")
                        .multilineTextAlignment(.center)
                        .font(.caption2)
                }
            }
        }
    }
}
    

Initializing and Starting a Live Activity


The next step is to setup an initial state of the live activity and then call .request function to start the live activity.


if ActivityAuthorizationInfo().areActivitiesEnabled {

    let initialContentState = FootballScoreAttributes.ContentState(score: "0", time:0)
    
    let activityAttributes = FootballScoreAttributes(venue: venue)
    
    let activityContent = ActivityContent(state: initialContentState, staleDate: Calendar.current.date(byAdding: .minute, value: 100, to: Date())!)
    
    // Code to start the Live Activity.

    scoreActivity = Activity.request(attributes: activityAttributes, content: activityContent)


}
    

Updating Live Activity Data


Now as the data changes, we need to update the content of the live activity. Use .update function to achieve the same.


let updatedScoreStatus = FootballScoreAttributes.GameStatus(score: score, time:time)

let alertConfiguration = AlertConfiguration(title: "Score Update", body: description, sound: .default)

let updatedContent = ActivityContent(state: updatedScoreStatus, staleDate: nil)

await scoreActivity?.update(updatedContent, alertConfiguration: alertConfiguration)

Conclusion


Now we have implemented Live Activities in our app and provided users with real-time updates and interactive functionality right in the Dynamic Island. With Live Activities, you can keep your users engaged and informed, enhancing their overall experience with your app.

Blog for Mobile App Developers, Testers and App Owners

 

This blog is from Finotes Team. Finotes is a lightweight mobile APM and bug detection tool for iOS and Android apps.

​

In this blog we talk about iOS and Android app development technologies, languages and frameworks like Java, Kotlin, Swift, Objective-C, Dart and Flutter that are used to build mobile apps. Read articles from Finotes team about good programming and software engineering practices, testing and QA practices, performance issues and bugs, concepts and techniques. 

bottom of page