无法保存数据并从关闭重新加载TableView

时间:2019-08-01 19:53:40

标签: swift swift5

我是Swift中的新手。我已经连接到websocket(使用Starscream),并且正在等待通过此方法接收文本或事件:

k

当我收到一个事件(只是ID)时,我从另一个视图控制器触发了func websocketDidReceiveMessage(socket: WebSocketClient, text: String) ;此func指向http请求(从服务器获取有关事件的所有信息),此func带有func fetchInfoAboutInvitations(text: String)

completion:

然后我返回fetchInfoAboutInvitations函数,以尝试执行以下操作:

func gettingInfoAboutInvitationAfterSocket(invitationId: String, completion: @escaping (Invitations) -> Void)

关于此:

info.getInfoAboutInvitationAfterSocket(invitationId: text)
{ (invitation) in
     print("some inv: \(invitation)") // -- here i got data
     self.arrList.append(invitation)
  DispatchQueue.main.async {
  self.tableViewController.reloadData()
}

我有我的数据打印输出,但是tableview为空。如果我重新运行应用程序,则表视图将不为空。另一个功能可以正常工作:

var arrList = [Invitations]() {
    didSet {
        print("arrList: \(arrList)")
    }
}

我的viewDidLoad:

func getCurrentEvent() {
    currentInvitations.getCurrentInvitations { (value) in
        print("currentInv value get CURINVI: \(value)")
        self.arrList.append(value)
        DispatchQueue.main.async {
            self.tableViewController.reloadData()
        }
    }
}

我想我不能在var arrList = Invitations中追加数据的原因是因为我在viewDidLoad中没有func fetchInfoAboutInvitations(text:String),但是我不能添加它,因为它是一个闭包

更新:

override func viewDidLoad() {
    super.viewDidLoad()
    tableViewController.delegate = self
    tableViewController.dataSource = self
    getCurrentEvent()
}

更新#2,添加一些细节: 在这里,我从websocket(server)获取事件

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return arrList.count
}


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell = tableViewController.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? EventControllerCell {
        cell.nameLabel.text = arrList[indexPath.row].id
        return cell
    }
    return UITableViewCell()
}

然后我触发:

func websocketDidReceiveMessage(socket: WebSocketClient, text: String) {
      print("websocketDidReceiveMessage text: \(text)")
        do {
            let welcome = try? JSONDecoder().decode(Welcome.self, from: text.data(using: .utf8)!)
            print("welcome: \(String(describing: welcome))")
            print("welcome dataDataId: \(String(describing: welcome?.data.data.objectID))")
            print("welcome eventType: \(String(describing: welcome?.data.eventType))")

            if let invitationId = welcome?.data.data.objectID {

                let event = EventController()
                event.fetchInfoAboutInvitations(text: invitationId)

            }
        }

请求完成:

func fetchInfoAboutInvitations(text: String) {
    let info = InfoAboutInvitation()
    info.getInfoAboutInvitationAfterSocket(invitationId: text) { (invitation) in
        print("some inv: \(invitation)")
        self.arrList.append(invitation)
        DispatchQueue.main.async {
            self.tableViewController.reloadData()
        }
    }
}

如果问题仍未解决,请问有人可以通过另一种方式实现这一点吗?我不知道如何将其与委托人\协议(以及如何实现)配合使用。

我在另一台PC上运行了该应用程序,现在当关闭有效时,tableView中的值为空:

func getInfoAboutInvitationAfterSocket (invitationId: String, completion: @escaping (Invitations) -> Void) {

    guard var urlComp = URLComponents(string: "") else {return}
    urlComp.path = ""
    guard let url = urlComp.url else { return }

    var request = URLRequest(url: url)
    request.httpMethod = "GET"
    request.setValue("a")
    request.addValue("", forHTTPHeaderField: "")

    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        if error != nil {
            print("URLSession error")
            print(error!)
        }

        guard let data = data else {
            print("data is empty")
            return
        }

        do {
            let getData = try! JSONDecoder().decode(Invite.self, from: data)

            let invitionData = Invitations(id: getData.id, initiator: getData.initiator, receiver: getData.receiver, group: getData.group, created: nil, status: getData.status, replieadAt: getData.replieadAt)
                print("info about invitationData (infAbout): \(invitionData)")
                completion(invitionData)
        } catch let err {
            print(err)
        }

    }
    task.resume()
}

1 个答案:

答案 0 :(得分:0)

如果tableViewController是UITableViewController的实例,则需要在UITableViewController的reloadData()属性上调用tableView,例如self.tableViewController.tableView.reloadData()