Search code examples
iosswiftsocketsmobilesockjs

Connect iOS app to sockJs server using swift


I am working on iOS app and I have to connect my app to sockJS server to get live feed. Is there any sockJS client available for iOS. Thanks in advance.


Solution

  • Connected successfully to SockJS using the following :)

    1. Place a UIWebView and set its visibility to hidden.
    2. Use SockJS client in webview.
    3. Use UIWebViewDelegate.
    4. We have to call the JS function only once from native swift code.

    ViewController:

    func initWebView(){
        webView = UIWebView()
        webView.frame = CGRectMake(0, self.view.frame.height-120, self.view.frame.width, 58)
        if let url = NSBundle.mainBundle().URLForResource("template", withExtension: "html", subdirectory: "web") {
            let requestURL = NSURLRequest(URL: url)
            //print("request\(requestURL)")
            webView!.delegate = self
            webView!.loadRequest(requestURL)
        }
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        print("WebView Loaded")
        if self.webViewLoaded == false {
            webView.stringByEvaluatingJavaScriptFromString("connectToSocket('\(self.serverUrl)','\(self.accessKey)')");
            //print("Sock return: \(htmlTitle)")
        }
        self.webViewLoaded = true
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    
        if request.URL!.scheme == "sockjs" {
            dispatch_async(dispatch_get_main_queue(), {
                let urlComponents = NSURLComponents(string: (request.URL?.absoluteString)!)
                let queryItems = urlComponents?.queryItems
                let param1 = queryItems?.filter({$0.name == "msg"}).first
                let temp = String(param1!.value!)
                if let data = temp.dataUsingEncoding(NSUTF8StringEncoding) {
                    let json = JSON(data: data)
                    //print("Live Data: \(json)")
                    self.updateMarkerInfo(json)
                }
            })
            return false
        }
    
        return true
    }
    

    template.html:

    Copy sockjs code in template.html, then add following.

    <script type="text/javascript">
    var sock;
        function connectToSocket(url, accessKey){
            //alert("connectTosocket called!");
            this.sock = new SockJS(url);
    
            sock.onopen = function() {
                //alert("open");
                sock.send(JSON.stringify({
                    key: accessKey
                }));
            };
    
            sock.onclose = function() {
                sock.close();
                alert("close");
            };
    
            sock.onmessage = function(e) {
                result = e.data.replace(/,\s*$/, '');
                window.location = 'sockjs://data?msg='+ result
                //alert(result);
            };
    
            sock.onerror = function(e) {
                alert("error" + e);
            };
        }
    
        function closeConnection () {
           try {
              this.sock.close();
              }catch(err) {
    
             }
           }
    
         function sendMessage(message){
            sock.send(message);
         }
    
    
    </script>
    

    Don't forget to add following in info.plist

    <key>NSAppTransportSecurity</key>
        <dict>
             <key>NSAllowsArbitraryLoads</key>
             <true/>
        </dict>
    

    https://github.com/vishal-raj/SockJSiOSClient