I'm trying to use URLRequest.CachePolicy.useProtocolCachePolicy
in my watch extension, but every request fails with 'can’t load from network' error.
I have seen the below answer:
NSURLErrorDomain Code=-2000 "can’t load from network"
but what I want to do is use cached if valid or request policy. The best fit is to use reloadRevalidatingCacheData
but it hasn't been implemented.
@constant NSURLRequestReloadRevalidatingCacheData Specifies that the existing cache data may be used provided the origin source confirms its validity, otherwise the URL is loaded from the origin source. Unimplemented.
In iOS, the useProtocolCachePolicy
works very similarly with reloadRevalidatingCacheData
.
https://developer.apple.com/documentation/foundation/nsurlrequest/cachepolicy/useprotocolcachepolicy
But the requests fail in watchOS with useProtocolCachePolicy
policy. It worked with reloadIgnoringLocalCacheData
by the way.
I'm not making HTTP or HTTPS byte-range request, so it seems like useProtocolCachePolicy
work as iOS does, but it doesn't.
The only way seems to implement caching manually, but I want to know why it doesn't work and there is any out-of-box option for this issue.
I got an answer from Apple about this issue.
Watch apps tend to be suspended very quickly so we recommend that developers use a background url session to ensure their api calls are still performed should an event such as backgrounding or suspension occur.
If anyone want to use .useProtocolCachePolicy policy, use background configuration.
let configuration = URLSessionConfiguration.background(withIdentifier: "xxx.xxx.xxxxx")
let session = URLSession(configuration: configuration)