How to Pass a Completion Block to Another Class in Swift

How to pass a completion block to another class in Swift

Here's the equivalent pieces that you need in Swift:

typealias AddedCompletionBlock = (saved: Bool, primaryKey: String, recordCount: Int) -> Void

var completionBlock: AddedCompletionBlock? = nil

completionBlock = {saved, primaryKey, recordCount in
print("\(saved), \(primaryKey), \(recordCount)")
}

completionBlock?(saved: true, primaryKey: "key", recordCount: 1)

You probably want to have a good read of the "Function Types" and "Closures" sections of the Apple Swift docs.

Passing a completion handler nested into another class

The problem is your completionHandler is not a completion handler:

public class func searchMovie(
name: String, completionHandler: (Result<[MovieInfo],Error>))

It is merely a Result object. A handler is a function:

public class func searchMovie(
name: String, completionHandler: (Result<[MovieInfo],Error>) -> Void)

Now you have a completion handler that you can call with a Result parameter.

Accessing variable out completion block

By default, calling checkCreateTabPermission as:

checkCreateTabPermission { pass, employee, cancel in
// here you can use the `employee`
}

should make you able to access the returned employee. So, you could call the needed method inside the completion of checkCreateTabPermission:

checkCreateTabPermission { pass, employee, cancel in
myMethod(employee: employee)
}

Or if you want to access the employee outside of the completion, you could declare a variable (which is nil by default) to hold its value once it returned:

var myEmployee: Employee?

checkCreateTabPermission { [weak self] pass, employee, cancel in
self?.myEmployee = employee
}

// you could use `myEmployee` here, but you have to make sure its not nil,
// in other words, `checkCreateTabPermission` has been called and retrieved one.
if let myUnwrappedEmployee = myEmployee {
// use `myUnwrappedEmployee`...
}

pass completion block from swift to back to objective

You can call TestViewController.completionData like this: self.completionData?(false, error) or self.completionData?(false, nil) if you don't want to pass error.

How i can pass the completion handler to another function swift ios

Replace

self.finishCreatingConversation(conversationId: conversationId, message: message, completion: completion)

with

self.finishCreatingConversation(conversationId: conversationId, message: message) { res in
completion(res)
}

How to write a completion handler in a separated block of code in Swift with parameters out of scope

Ok based on our comments above, this is the route I would try: Write a short completion handler that calls your longer completion handler, passing the variables that are out of scope.

let task = URLSession.shared.dataTask(with: requestImagemGrafica) { data, response, error in

myCompletionHandler(data, response, error, marca, myUploadGroupMarcas)

}

Then you add two parameters to your completion handler in the function definition:

let myCompletionHandler: (Data?, URLResponse?, Error?, MarcaClass, myUploadGroupMarcas) -> Void

Obviously you need to replace MarcaClass with the actual class type that is marca and myUploadGroupMarcas seems to be a function so you'd need to write an appropriate parameter type for that.

How to call function with completion handler and parameters

Use like this:

func downloadRepositories(parameter1: String, parameter2: String, completed: @escaping () -> ()) {

let parameters: Parameters = [ "parameterA": parameter, "parameterB": parameter2 ]

Alamofire.request(url, parameters: parameters).responseJSON {
//response
completed()
}

Pass function to completion handler

If you want to pass your own closure as an input argument to UIView.animate, you need to match the types of the closures, so myCompletionHandler has to have a type of ((Bool) -> ())?, just like completion.

func hide(animated: Bool, myCompletionHandler: ((Bool) -> ())?) {
if animated {
transform = CGAffineTransform(scaleX: 0.7, y: 0.7)

UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: [], animations: {
self.alpha = 0
self.transform = CGAffineTransform.identity
}, completion: myCompletionHandler) // I want to run 'myCompletionHandler' in this completion handler
}
}

This is how you can call it:

hudView.hide(animated: true, myCompletionHandler: { success in
//animation is complete
})

Swift: how to pass a value received from delegate to a function's completion block?

You could add a completion block as parameter to the captureImage method. Assign it to the completion parameter of the CameraEngine engine class. When the photoOutput is received you can just use this completion block. Here's how:

class CameraEngine: NSObject {

private var capturedImageData: Data?
//...
var completion: ((Data?) -> Void)?
func captureImage(completion: @escaping (Data?) -> Void) {
self.completion = completion
//...
}
//...
}
extension CameraEngine: AVCapturePhotoCaptureDelegate {
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
completion?(photo.fileDataRepresentation())
}
}

Usage:

let cameraEngine = CameraEngine()
cameraEngine.captureImage { data in
print(data)
}


Related Topics



Leave a reply



Submit