websocket事件中的swift API调用

时间:2018-05-05 08:56:34

标签: swift rest api websocket

我正在swift4上制作聊天应用。我使用python3 + django使用服务器端系统。

我的聊天客户端可以很好地与我的服务器端系统通信,除非在我的套接字事件中调用ajax函数。

这是我的代码。

func reloadChatData() {
    let jsonData = loadChat(_registration_id: RemoshinData.getRegistrationId())

    if(jsonData["status"].string! == "success") {
        for chat in jsonData["chat"].arrayValue {
            if (chat["chat_from"] == "D") {
                let chat = ChatEntity(text: chat["chat"].string!, time: "", userType: .You)
                chats.append(chat)
            }
            else {
                let chat = ChatEntity(text: chat["chat"].string!, time: "", userType: .I)
                chats.append(chat)
            }
        }
    }
    tableView.reloadData()

}

func loadChat(_registration_id: String) -> JSON {
    let _commonURL = CommmonURL()
    var _load_chat_url = _commonURL.SERVER_HOSTNAME + _commonURL.LOAD_CHAT_ENTRY_POINT

    _load_chat_url = addParameter(url: _load_chat_url, named: "registration_id", value: _registration_id)
    let response = runQuery(_load_chat_url)
    let data: Data? = String(describing: response.rawValue).data(using: .utf8)
    let responseJson = JSON(data!) as JSON
    return responseJson
}

private func runQuery(_ _url: String) -> JSON {
    var responseData: JSON = JSON.null
    let urlString = _url
    var keepAlive = true

    Alamofire.request(urlString, method: .get, parameters: nil, encoding: JSONEncoding.default).responseJSON(completionHandler: { response in
        responseData = JSON(response.result.value!)
        keepAlive = false
        print("**")  // ********** When I call runQuery from websocket event listener function, the code don't reach this line.   **********
    })

    print(keepAlive)
    let runLoop = RunLoop.current
    while keepAlive &&
        runLoop.run(mode: RunLoopMode.defaultRunLoopMode, before: Date(timeIntervalSinceNow: 0.1)) {
    }

    return responseData
}

我可以成功地从viewController调用reloadChatData函数。

但以下电话不起作用。

override func viewDidLoad() {

    manager = SocketManager(socketURL: URL(string: SocketURL)!, config: [.log(true), .compress])
    socketIOClient = manager.defaultSocket

    socketIOClient.on(clientEvent: .connect) {data, ack in
        print(data)

        // Connect Event is fired...
        let data : Dictionary<String, String> = ["value": RemoshinData.getRegistrationId()]
        self.socketIOClient.emit("join_room", data)
        print("socket connected")
    }

    socketIOClient.on(clientEvent: .error) { (data, eck) in
        print(data)
        print("socket error")
    }

    socketIOClient.on(clientEvent: .disconnect) { (data, eck) in
        print(data)
        print("socket disconnect")
    }

    socketIOClient.on(clientEvent: SocketClientEvent.reconnect) { (data, eck) in
        print(data)
        print("socket reconnect")
    }

    socketIOClient.on("server_to_client") { data, emitter in
        print("Get Message from Doctor...")

        // ********** FAILED **********
        self.reloadChatData()
    }

    socketIOClient.connect()

}

我在控制台上收到了“从医生处获取消息...”消息。但reloadChatData函数似乎永远不会结束。

我知道runQuery函数中的keepAlive变量永远不会改变false,所以while循环不能结束。 我该如何解决这个问题?请给我一个建议。

0 个答案:

没有答案