【问题标题】:Can't save data and reloadTableView from closure无法保存数据并从关闭中重新加载表视图
【发布时间】:2019-08-01 19:53:40
【问题描述】:

我是 Swift 的新手。我有一个到 websocket 的连接(使用 Starscream),我正在等待以这种方法接收文本或事件:

func websocketDidReceiveMessage(socket: WebSocketClient, text: String)

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

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

然后我回到 fetchInfoAboutInvitations 函数,以尝试:

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

关于这个:

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

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

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

我的 viewDidLoad:

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

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

更新:

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()
}

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

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()
        }
    }
}

完成的请求:

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()
}

如果问题不清楚,有人可以告诉我如何用另一种方式实现这一点吗?我不知道如何将它与 delegates\protocols 一起使用(以及如何实现它)。

我在另一台 PC 上运行该应用程序,现在我在 tableView 中有 null,当关闭工作时:

func fetchInfoAboutInvitations(text: String) {

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

【问题讨论】:

    标签: swift swift5


    【解决方案1】:

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

    【讨论】:

    • 不,它的 UITableView
    • 您能分享一下您的func tableView(UITableView, numberOfRowsInSection: Int) -> Intfunc numberOfSections(in: UITableView) -> Intfunc numberOfSections(in: UITableView) -> Int 实现吗?
    • 我在主帖中添加了“更新”当我第一次运行应用程序时(当工作方法 viewDidLoad 时)我的 tableView 不是空的(如果我有一些事件)。问题在于更新 tableView 中的新事件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    • 2021-10-23
    • 1970-01-01
    • 2014-07-02
    • 2011-03-23
    • 1970-01-01
    • 2020-12-16
    相关资源
    最近更新 更多