最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ios - How to make LiveActivityIntent run for extended period of time? - Stack Overflow

programmeradmin3浏览0评论

I have a LiveActivityIntent where I want to check and display live internet speed on a LiveActivity for 30 second. But currently the code just shows 9-10 seconds and pauses the further execution.

struct ShowSpeedIntent: LiveActivityIntent {
    static var title: LocalizedStringResource = "Start"

    func perform() async throws -> some IntentResult {
        guard ActivityAuthorizationInfo().areActivitiesEnabled else {
            return .result()
        }

        do {
            let activity = try Activity.request(
                attributes: ShowSpeedAttributes(name: "tests"),
                content: .init(
                    state: ShowSpeedAttributes.ContentState(emoji: "ABC"),
                    staleDate: Date().addingTimeInterval(1)
                )
            )

            let counter = SpeedMeterCounter()
            counter.measure() // Start the measurement

            // Run a loop for 30 seconds, updating every second
            for i in 0 ..< 30 {
                if let speed = counter.trafficStatuses.first?.displaySentSpeed {
                    Logger.showSpeedIntent.info("[ShowSpeedIntent] \(i) Measured Speed: \(speed)")

                    await activity.update(
                        ActivityContent(
                            state: ShowSpeedAttributes.ContentState(emoji: "\(i) - \(speed)"),
                            staleDate: nil
                        )
                    )
                }

                do {
                    try await Task.sleep(nanoseconds: 1_000_000_000) // Sleep for 1 second
                } catch {
                    Logger.showSpeedIntent.info("Sleep interrupted: \(error)")
                    break
                }
            }

            counter.stop() // Stop measuring
            Logger.showSpeedIntent.info("Counter stopped. Ending activity.")

            // End the activity after the loop completes
            await activity.end(dismissalPolicy: .immediate)

        } catch {
            Logger.showSpeedIntent.info("Error starting activity: \(error)")
        }

        return .result()
    }
}

I have tried ussing a heavy for loop instead Task.sleep to update the LiveActivity every second.

Is there any way to run my LiveActivityIntent to show 30 seconds (or more if possible) worth live data? Or is there any other approach I can use?

发布评论

评论列表(0)

  1. 暂无评论