0

I have an array of UIImage's that I want to upload to my S3 instance in Swift. Below is my code for uploading them:

 func sendImageMessage(photo : UIImage)  {
        s3Uploader.uploadFile(withImage: photo) { [self] (url) in
            processMessage(ourShip: ourShip!, shipUrlString: shipURLString, chatShip: airlockStore.selectedChannel.channelShip, chatName: airlockStore.selectedChannel.channelName, text: url, index: idx)
            sendPendingMessage(text: url)
        }
    }

Here is my code where I'm getting the array of images from a camera input bar in a chat view:

   func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith attachments: [AttachmentManager.Attachment]) {
        
        for item in attachments {
            if  case .image(let image) = item {
                 self.sendImageMessage(photo: image)
            }
        }
        inputBar.invalidatePlugins()
    }

The issue I'm having is that if multiple images are selected, the sendImageMessage gets called again for each item before the first item has finished uploading.

I've tried using closures to pause my loop from going to the next item in the images array until the first one has been uploaded, but haven't been able to get this to work.

narner
  • 2,908
  • 3
  • 26
  • 63
  • 1
    Does it matter that you send multiple uploads at once? It will be faster to do so. – Paulw11 May 13 '21 at 21:54
  • @Paulw11 I think so; I need to get the urls for each image that's uploaded; not just upload them and move on – narner May 13 '21 at 21:56
  • 1
    Ok, but that's a different question. Why can't you collect all of the urls? Is your real question that you want to know when all of the asynchronous uploads are complete? If so, you can use a `DispatchGroup` – Paulw11 May 13 '21 at 22:04
  • @Paulw11 Kind of; basically what is currently happening is that the second image gets uploaded twice; the first one gets cancelled out – narner May 13 '21 at 22:07
  • I've been trying to follow the accepted answer here: https://stackoverflow.com/questions/35906568/wait-until-swift-for-loop-with-asynchronous-network-requests-finishes-executing – narner May 13 '21 at 22:40

0 Answers0