Hi, I'm encountering some issues with Ktor on iOS....
# ktor
u
Hi, I'm encountering some issues with Ktor on iOS. I'm developing an AI chat app, and when sending requests and generating content, if I switch to the desktop and the app goes to the background, I notice the response stream pauses. When bringing the app back to the foreground, it displays...
Copy code
2025-09-29 00:09:26.282244+0800 RikkaHub[39983:9709569] [Default] Task <2E420780-3E77-40C3-B2D4-199855E3C03D>.<5> terminated due to error [-997] Error domain=NSURLErrorDomain Code=-997 "Connection to background transfer service lost" UserInfo={NSErrorFailingURLStringKey=<https://api.siliconflow.cn/v1/chat/completions>, NSErrorFailingURLKey=<https://api.siliconflow.cn/v1/chat/completions>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"BackgroundDataTask <2E420780-3E77-40C3-B2D4-199855E3C03D>.<5>",
Local Data Task <2E420780-3E77-40C3-B2D4-199855E3C03D>.<5>
NSURLErrorFailingURLSessionTaskErrorKey=BackgroundDataTask <2E420780-3E77-40C3-B2D4-199855E3C03D>.<5>, NSLocalizedDescription=Connection to the background transfer service lost}
Copy code
actual fun httpClientEngine(): HttpClientEngine {
    return Darwin.create {
        configureRequest {
            setAllowsCellularAccess(true)
            setAllowsExpensiveNetworkAccess(true)
            setAllowsConstrainedNetworkAccess(true)

            setNetworkServiceType(NSURLNetworkServiceTypeBackground)
        }
        val config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(
            "me.rerere.rikkahub.background"
        )
        config.sessionSendsLaunchEvents = true

        val delegate = KtorNSURLSessionDelegate()
        val backgroundSession = NSURLSession.sessionWithConfiguration(
            configuration = config,
            delegate = delegate,
            delegateQueue = null
        )

        usePreconfiguredSession(backgroundSession, delegate)
    }
}
This is the configuration for the Darwin engine, I have already set up background mode in Xcode. How can I enable the app to continue receiving network response while moving to background?
a
The problem might be that we use the
dataTaskWithRequest
method, which, according to this StackOverflow answer, cannot be executed in the background.