我试图在目标C类中调用包含完成处理程序的Swift函数,但我不确定如何实现它。
这是我的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
}
如何在目标c中编写函数调用。我已经完成了项目的设置,以便我可以从目标c调用快速函数。
答案 0 :(得分:5)
例如,您有以下代码:
@objc class PDTextToSpeech: NSObject{
func toSpeech(word: NSString, success: () -> Void) -> NSURL {
// ...
return NSURL()
}
}
因此,您可以轻松地将obj-c中的Swift代码与项目名称的#import "<ModuleName>-Swift.h"
联系起来。
然后你可以打电话:
[[PDTextToSpeech new] toSpeech:@"String" success:^{
NSLog(@"Success");
}];
我使用PDTextToSpeech
作为类名,因为使用uniq前缀调用obj-c中的类更可取。如果您调用名为TestProject
的项目 - 您可以使用TP
前缀。
答案 1 :(得分:2)
我想它应该是这样的:
textToSpeech* text = [[textToSpeech alloc] init];
[text word:@"some text" sucess:^{
NSLog(@"success");
}];