Reputation: 231
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)
print("createdURL")
print(tempFile)
sucess();
}
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.
Upvotes: 4
Views: 1670
Reputation: 1710
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:^{
NSLog(@"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.
Upvotes: 6
Reputation: 2229
I guess it should look like this:
textToSpeech* text = [[textToSpeech alloc] init];
[text word:@"some text" sucess:^{
NSLog(@"success");
}];
Upvotes: 3