0

I am implementing dragging and dropping images from, let say, Safari into a collectionView of my own app. I need the both the UIImage and image url from the dragItem.

The way to get any of them is to use UIDragItem.itemProvider.loadObject. But since loadObject(ofClass:completionHandler:) runs asynchronously, how can I make sure there will be no race condition with the code below?

(note: the two are in the performDropWith func, I want to make sure they execute in order because I need to do work immediately after the second one finishes)

var imageARAndURL = [String: Any]()

_ = item.dragItem.itemProvider.loadObject(ofClass: UIImage.self) { (provider, error) in
    if let image = provider as? UIImage {
        let aspectRatio = image.size.height / image.size.width
        print(aspectRatio)
        imageARAndURL["aspectRatio"] = aspectRatio
    }
}

_ = item.dragItem.itemProvider.loadObject(ofClass: URL.self) { (provider, error) in
    if let url = provider {
        print(url.imageURL)
        imageARAndURL["imageURL"] = url.imageURL
        print(imageARAndURL)
    }
}
Gang Fang
  • 787
  • 7
  • 14
  • 1
    You can use a `DispatchGroup` to wait until both tasks are complete and continue the execution with both values. [More info on this answer.](https://stackoverflow.com/a/42484670/725628) – EmilioPelaez Oct 19 '18 at 03:35
  • @EmilioPelaez - thanks for your answer. I will try that but I am also curious **if** there will be a race condition, it seems that the second loadObject, which is `loadObject(ofClass: URL.self)` would always execute after the first one, which means they seem to happen in order. And I check code sample online and found that people didn't use `DispatchGroup` for that (this is a homework assignment). – Gang Fang Oct 19 '18 at 03:44
  • 1
    If it's asynchronous then you simply can't guarantee that it will happen in order, so yes, there will be a race condition; it might work correctly every time, or it might fail when you less expect it, or on a different device (like your professor's). There is a concept called "Defensive Programming", where you implement safeguards for errors you haven't encountered yet. If this is an assignment, I would encourage you to implement it with the `DispatchGroup`, worst case scenario is that you learned to use an important tool. – EmilioPelaez Oct 19 '18 at 04:09

0 Answers0