2
查看凍結而數據是獲取並顯示。根據我的理解,fetchBoard()
和initUserInfo()
不會並行執行。 (僅當加載板時fetchBoard()
才加載視圖) 我擔心如果使用DispatchQueue.main.async
多次凍結視圖。另外,如何使其順利運行。查看與多個DispatchQueue.main.async凍結使用
class MultipleCardsController2vs2: BaseController, UICollectionViewDataSource , UICollectionViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let repo = GameRepository()
repo.CreateGame(gameID : self.jsonGame.Id , completion: { (jsonGame, err) -> Void in
if(err == ErrorCode.NoError){
DispatchQueue.main.async{
self.jsonGame = jsonGame
}
}
})
//These are the two functions I want these 2 to work in parallel
self.fetchBoard() //Function 1
self.initUserInfo() //Function 2
collectionView.delegate = self
collectionView.dataSource = self
} // .viewDidLoad
func fetchBoard(){
let repo = GameRepository()
self.sortedBoardArr.reserveCapacity(self.BoardArr.count)
let serialQueue = DispatchQueue(label: "serialQueue")
let group = DispatchGroup()
for board in self.jsonGame.boards{
group.enter()
serialQueue.async {
repo.GetBoardInfo(gameID: self.jsonGame.Id, boardID: board , completion : {(response , errorCode) -> Void in
if errorCode == ErrorCode.NoError{
self.BoardArr.append(response)
group.leave()
}
})
DispatchQueue.main.async{
//Main async - 1
group.wait()
self.sortArr()
self.collectionView.reloadData()
}
}
}
}
func sortArr(){
if self.jsonGame.boards.count == self.BoardArr.count{
for board in self.jsonGame.boards{
for boardarr in self.BoardArr{
if boardarr.id == board{
self.sortedBoardArr.append(boardarr)
}
}
}
}
}
fileprivate func initUserInfo()
{
DispatchQueue.main.async{
//Main async - 2
self.name1.text = self.CurrentUser.UserName
self.imgPlayie1.image = UserManager.GetAvatar(user: self.CurrentUser)
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.jsonGame.boards.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Round2Cell", for: indexPath) as! Round1vs1cell
cell.background.backgroundColor = UIColor(white: 1, alpha: 0.0)
cell = self.populateGameCell(game_res, cell , indexPath)
return cell
}
fileprivate func populateGameCell(_ game_res: Game_Res, _ cell: Round1vs1cell , _ indexPath : IndexPath) -> Round1vs1cell
{
DispatchQueue.main.async {
//Main async - 3
cell.background.backgroundColor = UIColor(white: 1, alpha: 0.0)
cell.word_1.text = game_res.words[0].word
cell.color_1.image = UIImage(named: "")
cell.life_1.image = UIImage(named: "")
cell.name.text = ""
cell.op_name.text = game_res.master[index].username
cell.timeout_left.image = UIImage(named: "Hourglass.png")
cell.round.text = "Round: \(indexPath.row + 1)"
}
return cell
}
}
尋找順利的工作,而不是凍結視圖。我很樂意與Dispatch合作。歡迎任何幫助。提前致謝。
工程就像一個魅力。謝謝哥們 :) – Prateekro