Created
December 31, 2016 12:36
-
-
Save grandadmiral-thrawn/682577287838463ba096b3c58d5f056b to your computer and use it in GitHub Desktop.
Node Websocket and native JSON parsing in Swift for socket.io type sockets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This should go in your main ViewController or GameViewController. Some sockets want it in AppDelegate.swift. Using Starscream Socket here. | |
func websocketDidReceiveMessage(socket: WebSocket, text: String) { | |
//print("Received text: \(text)")] | |
// decode data | |
var data = text.data(using: .utf8)! | |
// data is like {message: "hi", data: "[{"tagId": "long number here", ...},{"tagId": "long number here"}]"} | |
if let parsedData = try? JSONSerialization.jsonObject(with: data) as! NSDictionary { | |
// value of the "data" key is actually array | |
let arrayed = parsedData["data"] as! NSArray | |
//check that it's array | |
print(arrayed[0]) | |
// because the next step is to map reduce. check that fist value. it should also be a dictionary like : {"tagId": "long number here", "date": "some date here", ...} | |
let mapped = arrayed[0] as! NSDictionary | |
print(mapped) | |
let tagId = mapped["tagId"] | |
print(tagId) | |
// what comes back is an optional containing tagId's value, which in this case is a long number expressed as string. | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment