我正在尝试使用我的SendBird聊天应用程序中可用的聊天频道数初始化变量channels
。我在此过程中使用了一个名为private func loadChannels()
的函数,以便将通道加载到上面提到的变量中。我不明白的是,在调用函数时会加载通道,并且可以显示,如下面的代码所示。但是,当我想在channels
之外显示相同变量loadChannels()
的内容时,我得到一个空变量。可能是什么问题?
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)
})
}
答案 0 :(得分:1)
你可以这样做:
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(callback: @escaping () -> void) {
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)
callback()
})
}