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

标签 ios swift sockets mobile sockjs

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

最佳答案

使用以下命令成功连接到 SockJS :)

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

View Controller :

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

关于ios - 使用 swift 将 iOS 应用程序连接到 sockJs 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38849598/

相关文章:

ios - 显示窗口级别的 View UIWindowLevelStatusBar 退出当前的第一响应者

python 2.7.8 : Socket - Client Server Data loss in TCP socket

c++ - 在 C++ 中通过套接字发送图像

java - 通过套接字将声音从android发送到PC时出现噪音

ios - 如何向 Web View 应用程序添加上边距?

ios - Xcode UIAutomation 无法与 TTTAttributedLabel 交互

ios - 拍照时应用程序崩溃且没有错误

swift - 如何为 iOS 7 和 iOS 8 实现搜索 Controller

ios - UICollectionViewCell 有 2 个单元格,每个单元格的高度为 "wrap_content"

ios - 用户打字时覆盖变暗