如何在Swift 3中接收JSON响应

时间:2017-03-22 22:27:29

标签: json swift3

在与服务器通信时,我试图找出发送和接收JSON与Swift3的语法有很多困难。到目前为止,我在Connection类中有以下代码:


import Foundation

class Connection: NSObject, GCDAsyncSocketDelegate {

    var socket: GCDAsyncSocket!

    func open(host: String, port: UInt16) {

        print("Attempting connection on Host: \(host) at Port: \(port)")
        socket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main)

        do {
            try socket.connect(toHost: host, onPort: port)
        } catch let e {
            print(e)
        }
    }

    func socket(_ socket: GCDAsyncSocket, didConnectToHost host: String, port p: UInt16) {

        print("Connected to \(host) on port \(p)")

        let sendJSON = try? JSONSerialization.data(withJSONObject: ["NAME":"JERRY","TYPE":"CONNECT"], options: [])

        socket.write(sendJSON!, withTimeout: -1, tag: 0)

        let data = Data()

        //socket.readData(to: data, withTimeout: -1, tag: 1)

        let recJSON = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as! [String : AnyObject]

        socket.readData(to: data, withTimeout: -1, tag: 1)
        let parseJSON = recJSON?["TYPE"]

        print("data: \(data)")
        print("parseJSON: \(parseJSON)")
        print("recJSON: \(recJSON)")
        print("sendJSON: \(sendJSON)")

        socket.disconnect()
        print("Disconnecting")
    }

    func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {

        print("Error: \(Error.self)")
    }
}

服务器要求以下列形式发送单个JSON对象:

{"NAME":<name>, "TYPE":"CONNECT"} 

正如您在上面的Connection类代码中所看到的,那是发送的,当我查看终端中的服务器输出时,我看到:

Connection established
Received: {"NAME":"JERRY","TYPE":"CONNECT"}
{ "TYPE": "CONNECT_RESPONSE" }

我现在想解析来自服务器的应用程序中的响应:

{ "TYPE":"CONNECT_RESPONSE" }

我已经尝试了几十个场景,并在Stackoverflow上阅读了大量的Swift条目,但是没有任何工作。当我使用&#39; Parsed响应&#39;运行应用程序时打印线,我刚刚得到了#nil&#39;。任何人都能解释一下吗?请?

编辑:

尝试修改后,

    print("data: \(data)")
    print("parseJSON: \(parseJSON)")
    print("recJSON: \(recJSON)")
    print("sendJSON: \(sendJSON)")

...然后测试,我收到了以下内容:

Connected to xxx.xxx.xxx.xxx on port 8889
data: 0 bytes
parseJSON: nil
recJSON: nil
sendJSON: Optional(33 bytes)
Disconnecting

1 个答案:

答案 0 :(得分:0)

而不是使用

let parseJSON = json?["TYPE"]

尝试:

let parseJSON = recJson?["TYPE"]

另外,尝试同时打印:

print(data)
print(recJson)

确保您收到回复。有点像淘汰的过程。