【问题标题】:Connect iOS app to sockJs server using swift使用 swift 将 iOS 应用程序连接到 sockJs 服务器
【发布时间】:2016-12-15 10:22:38
【问题描述】:

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

【问题讨论】:

    标签: ios swift sockets mobile sockjs


    【解决方案1】:

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

    1. 放置一个 UIWebView 并将其可见性设置为隐藏。
    2. 在 webview 中使用 SockJS 客户端。
    3. 使用 UIWebViewDelegate。
    4. 我们只需要从原生 swift 代码调用 JS 函数一次。

    视图控制器:

    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:

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

    <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

    【讨论】:

    • webview 中的 SockJS 客户端是什么意思?你能解释一下第二点吗
    • 用 SockJS 客户端创建一个 html 文件,并在 webview 上使用。
    猜你喜欢
    • 2015-10-17
    • 2017-01-05
    • 1970-01-01
    • 2019-07-10
    • 2016-02-14
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    • 2016-08-16
    相关资源
    最近更新 更多