-1

I'm writing an app in Swift and I've run into a problem I can't find much help for.

So I've got a ViewController and a class named CameraHandler that uses calls the an ActionSheet which then presents camera or gallery picker and saves resulting images.

What I want to do is: call camera, save the image, and then store relevant information to an object.

     CameraHandler.shared.showActionSheet(vc: self, reg: car.registration) 

        self.car.imagePath = CameraHandler.shared.returnFilePath()
        self.storeCar() // completes before CameraHandler can get imagepath

My workaround is using a simple DispatchQueue to wait 10 secs hoping it completes in time.

user3398918
  • 71
  • 3
  • 10

2 Answers2

0

As matt says in his comment, don't wait. Don't expect the answer to be returned from your function. You need to rewrite your showActionSheet() function to take a completion handler. (That is a block of code {more specifically, a closure} that you pass as a parameter.) When your function gets an answer from the async process it needs to complete (fetching a value from a remote server, prompting the user for something, etc.) then it calls the completion handler.

See my answer to the thread below. I include a sample project that uses a function with a completion handler to fetch data from a remote server.

Swift: Wait for Firebase to load before return a function

Duncan C
  • 128,072
  • 22
  • 173
  • 272
0

Using a closure or block in other programing languages as a completion handler, let take an example.

func returnFilePath(completionHandler: ((String) -> ()) {
     // after get file path
     completionHandler(path)
}

then you can use it like:

returnFilePath { path in
     // do some thing with the path
}
tphduy
  • 119
  • 7