0
我试图初始化变量channels
与聊天频道,在我的SendBird聊天应用程序可用的数量越来越初始化。我为这个过程使用了一个函数:private func loadChannels()
,以便将通道加载到上述变量中。我不明白的是,调用函数时会加载通道,并且可以按照您在下面的代码中看到的方式显示。但是,当我想显示loadChannels()
之外的相同变量channels
的内容时,我得到一个空变量。可能是什么问题?变量未使用功能时完成处理
import UIKit
import SendBirdSDK
import JSQMessagesViewController
class ViewController: UIViewController {
var messages = [JSQMessage]()
var channels = [SBDOpenChannel]()
private var refreshControl: UIRefreshControl?
private var openChannelListQuery: SBDOpenChannelListQuery?
override func viewDidLoad() {
//connecting to the application
SBDMain.initWithApplicationId("1662A8E8-F45F-454B-9E5E-02362342ECC5")
//Connecting the user
SBDMain.connect(withUserId: "tahrisqalli", completionHandler: { (user, error) in
// ...
print("connected tahrisqalli")
print ("printing channels")
self.loadChannels()
print (self.channels)
print ("printing channels")
self.loadChannels()
// Here content of channels variable is empty
print (self.channels)
})
}
private func loadChannels() {
self.openChannelListQuery = SBDOpenChannel.createOpenChannelListQuery()
self.openChannelListQuery?.limit = 20
if self.openChannelListQuery?.hasNext == false {
return
}
self.openChannelListQuery?.loadNextPage(completionHandler: { (channels, error) in
if error != nil {
print ("error")
return
}
for channel in channels! {
self.channels.append(channel)
}
// Here content of channels is full with the correct channels
print (self.channels)
})
}
既然你在完成处理程序填补了'channels'财产,我的猜测是,这个处理器是尚未被调用(异步?)在调用loadChannels()后到达'print(...)'语句时。 – dfri
在这种情况下,我应该在哪里准确地称呼它? – user1680944
没有问题。在'self.loadChannels()'之后删除'print'行,因为 - 正如dfri已经提到的那样 - 这个方法异步工作,这个特殊的'print'行是没有意义的。 – vadian