HTTP Connections
On this page:
Warmup
By default, http(s) connections are kept open (in http v1.1 and up): when a client loads https://example.com/test1
, the connection to example.com (on port 443) remains open for a minutes (depends mainly on the server). As a result, when the client loads https://example.com/test2
later the connection overhead (DNS, TCP, TLS) is avoided. Depending on network conditions, that overhead can amount to 1 or more seconds (on fast connections it’s typically around 100ms).
When the app knows it will soon connect to a certain host (for example, connect to Kaltura for loading media info using the Media Providers), it will sometimes benefit from issuing a dummy request to the same host. This can be a basic GET.
For example, when loading media info from https://rest-as.ott.kaltura.com/...
, it’s a good idea to first load a generic request from this server - like https://rest-as.ott.kaltura.com/crossdomain.xml
.
Warmup in Swift
URLSession.shared.dataTask(with: URL(string: "https://rest-as.ott.kaltura.com/crossdomain.xml")!) { _,_,_ in
// Ignore the response
}.resume()
Warmup in Objective-C
[[NSURLSession.sharedSession dataTaskWithURL:[NSURL URLWithString:@"https://rest-as.ott.kaltura.com/crossdomain.xml"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// Ignore the response
}] resume];
Notes
- This code assumes the passed URL is valid and may crash if it isn’t. If the URL is not hard-coded (for example if it’s coming from a configuration file/server), it should be checked for validity (
URL(string:)
and[NSURL URLWithString:]
will return nil) - There’s no need to actually read the response or check for errors (other than maybe logging). There’s no harm if the request fails (you’ll just lose the warmup).
- These calls are asynchronous so it’s safe to call them from the main thread.
When to execute warmup?
In most cases it should be enough to run this code once, on app start. Depending on the app’s flow, however, it may be a good idea to run it closer to actual playback.