简体   繁体   中英

How to pass value to completion handler in Swift?

I would like to pass a integer to a completion handler. Because the handler is asynchronous the value of count might be inaccurate by the time the completion handler gets a chance to run? I would like to pass the CURRENT value of count to the handler so that count is accurate when the handler is called. How do I do this?

// Take image
    func didPressTakePhoto(){

        if let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo){

            videoConnection.videoOrientation = AVCaptureVideoOrientation.portrait

            count = count + 1

            //Capture image.  everything in this closure is ASYNCHRONOUS?
            stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: {
                (sampleBuffer, error) in

                //Do something with count...

            })
        }
    }

Since you have no declaration in this function for count , I will assume that count is a parameter. If so, then accessing count using self.count (mandatory in a block) will get the latest value of count , even if it changes after you call captureStillImageAsynchronously() .

If there is any chance that count can be written and read at the same time by multiple sources, you should ensure it is thread safe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM