Skip to content

Instantly share code, notes, and snippets.

@jaclync
Created April 24, 2017 17:37
Show Gist options
  • Save jaclync/13e215582dbac0ed8cdca881de7e1e5b to your computer and use it in GitHub Desktop.
Save jaclync/13e215582dbac0ed8cdca881de7e1e5b to your computer and use it in GitHub Desktop.
JSON <--> Dictionary
/// Dictionary --> JSON.
- (void)dictionaryToJson {
// `message: NSDictionary` to send to server.
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:message
options:0
error:nil];
[self.socket send:jsonData];
}
/// JSON --> Dictionary.
- (void)jsonToDictionary {
// `message: NSString` came back from socket.
NSData *objectData = [message dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:nil];
}
/// Dictionary --> JSON.
func send(messageDict: [String: Any]) {
do {
let messageData = try JSONSerialization.data(withJSONObject: messageDict, options: JSONSerialization.WritingOptions.prettyPrinted)
socket.send(messageData)
} catch (let error) {
fatalError("\(error)")
}
}
/// JSON --> Dictionary.
func webSocket(_ webSocket: SRWebSocket!, didReceiveMessage message: Any!) {
guard let message = message as? String,
let data = message.data(using: .utf8) else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)
guard let payload = json as? SocketManager.Payload else { return }
guard let command = ServerCommand(payload: payload) else { return }
delegate?.didReceive(command: command, payload: nil)
} catch (let error) {
fatalError("\(error)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment