Operate NSURLSession to establish webSocket with fallback to HTTPS

Hi,

I'd like to establish connection between my application and a remote server. Ideally it would be using webSocket since the communication is bi-directional and asynchronous.

However, In case the webSocket isn't established properly or failing sometime after it was created (due to firewall, proxy servers, network switching or any other reason), than I'd like to switch to using periodical simple HTTPS POST requests (keep alive messages) where the server-to-client data transferred on the responses. The server should also support both communication methods.

The following code should reflect my approach. Please advise if this could work or perhaps there are built-in solutions in the framework.

NSURL * reqUrl = [NSURL URLWithString:@"wss://mydomain.com"];

NSURLSession* session = [NSURLSession sessionWithConfiguration:
                            [NSURLSessionConfiguration defaultSessionConfiguration]];

NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:reqUrl];

webSocketTaskWithURL * socketConnection = [URLSession webSocketTaskWithURL:url];

socketConnection.resume()

[socketConnection sendMessage:message completionHandler: ^(NSError * e) {
    if (e != nil) { 
         // fallback to https 
         [req setHTTPBody:[message dataUsingEncoding:NSUTF8StringEncoding]]
         NSURLSessionDataTask *data_task_http = [session dataTaskWithRequest:req];        
         completionHandler:
                         ^(NSData * _Nullable data,
                           NSURLResponse * _Nullable
                           response,
                           NSError * _Nullable error) { /*blabla*/}];

          [data_task resume];
    }
Operate NSURLSession to establish webSocket with fallback to HTTPS
 
 
Q