Aaron Aaron - 4 months ago 6x
Objective-C Question

Call Swift function with completion handler in objective c

I am trying to call a Swift function that contains a completion handler in an objective C class, but I am not sure how to implement it.

This is my Swift Code

@objc class textToSpeech:NSObject{

func toSpeech(word: NSString, sucess:()->Void) -> NSURL {
let tempDirectory = NSURL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
let tempFile = tempDirectory.URLByAppendingPathComponent((word as String) + ".wav")

let tts = TextToSpeech(username: "xxxxxx", password: "xxxxxx")
tts.synthesize(word as String,
voice: SynthesisVoice.GB_Kate,
audioFormat: AudioFormat.WAV,
failure: { error in
print("error was generated \(error)")
}) { data in

data.writeToURL(tempFile, atomically: true)


return tempFile

How would I write the function call in objective c. I have already completed setting up the project so that I can call swift functions from objective c.


For example you have this code:

@objc class PDTextToSpeech: NSObject{
  func toSpeech(word: NSString, success: () -> Void) -> NSURL {
    // ...
    return NSURL()

So you could easily bridge you Swift code in obj-c with #import "<ModuleName>-Swift.h" where you project name.

Then you can call:

[[PDTextToSpeech new] toSpeech:@"String" success:^{

I was using PDTextToSpeech as class name, because it's preferable to call classes in obj-c with uniq prefix. If you project called TestProject - you can use TP prefix.