I'm developing an Photo editing application. I'm giving my users the option to import multiple assets to the edit View Controller
. I'm creating a Dispatch Group
for all the "PHAsset->Asset fetching" calls.
Each time the PHAsset
fetch request completion block called, I need to append
the fetched asset into an Mutable Array
, and updating the UI (1/3 imported | 2/3 imported and so on) by the amount of the imported assets.
Because Swift Mutable Arrays
aren't thread-safe, sometimes I'm getting a crash. I guess the completion handler called from multiple threads, causing some kind of a deadlock.
What would be the correct way to handle thread-safe read/write Array access with Concurrent Dispatch Group?
var assets = [Asset]()
func getAssetsFromPHAssets() {
let dispatchGroup: DispatchGroup = DispatchGroup()
for phAsset in phAssets {
dispatchGroup.enter() // Enter group for each asset
PHImageManager.default().requestPlayerItem(forVideo: phAsset, options: nil, resultHandler: { (item, info) in
let asset = Asset(playerItem: item, position: 0)
self.assets.append(asset)
DispatchQueue.main.async {
self.lblImport.text = "Importing \(self.assets.count)/3"
}
dispatchGroup.leave() // Leave group
})
}
dispatchGroup.notify(queue: DispatchQueue.main, execute: {
print("finished importing")
})
}