Created
April 24, 2017 17:37
-
-
Save jaclync/13e215582dbac0ed8cdca881de7e1e5b to your computer and use it in GitHub Desktop.
JSON <--> Dictionary
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
/// 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]; | |
} |
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
/// 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