我正在开发 iOS 应用程序,我必须将我的应用程序连接到 sockJS 服务器才能获得实时提要。是否有适用于 iOS 的 sockJS 客户端。提前致谢。
最佳答案
使用以下命令成功连接到 SockJS :)
- 放置一个 UIWebView 并将其可见性设置为隐藏。
- 在 webview 中使用 SockJS 客户端。
- 使用 UIWebViewDelegate。
- 我们只需从原生 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>
关于ios - 使用 swift 将 iOS 应用程序连接到 sockJs 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38849598/