使用swift将iOS应用程序连接到sockJs服务器

时间:2016-08-09 11:34:20

标签: ios swift sockets mobile sockjs

我正在开发iOS应用程序,我必须将我的应用程序连接到sockJS服务器以获取实时源。是否有适用于iOS的sockJS客户端。提前谢谢。

1 个答案:

答案 0 :(得分:2)

使用以下方法成功连接到SockJS:)

  1. 放置UIWebView并将其可见性设置为隐藏。
  2. 在webview中使用SockJS客户端。
  3. 使用UIWebViewDelegate。
  4. 我们只需要从本机swift代码调用JS函数一次。
  5. <强>的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:

    在template.html中复制sockjs代码,然后添加以下内容。

    <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>
    

    不要忘记在info.plist中添加以下内容

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

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