Search code examples
objective-cswift3swift-protocols

Can not find Swift Protocol declaration in Obj-C class


I have created on Class in Swift and that class and its protocol I am using in Obj-C enabled project but I am getting below error while compiling my project.

cannot find protocol declaration for 'SpeechRecognizerDelegate'; did you mean 'SFSpeechRecognizerDelegate'?

Can anyone guide me on this how can I use Swift class protocol in my Obj-C class.

Here is my Swift code:

protocol SpeechRecognizerDelegate : class  {
    func speechRecognitionFinished(_ transcription:String)
    func speechRecognitionError(_ error:Error)
}


class SpeechRecognizer: NSObject, SFSpeechRecognizerDelegate {
    open weak var delegate: SpeechRecognizerDelegate?

}

Protocol use in Obj-C:

#import "ARBot-Swift.h"

@interface ChatScreenViewController : JSQMessagesViewController <SpeechRecognizerDelegate>

Let me know if required more info.

Thanks in Advance.


Solution

  • Define your Swift protocol like this inside your Swift file.

    @objc protocol SpeechRecognizerDelegate: class{
      func speechRecognitionFinished(_ transcription:String)
      func speechRecognitionError(_ error:Error)
    }
    

    Create a Swift Module inside your project setting then use it. You can find here complete blog for the mix language coding.

    Then use Protocol inside Objective C class,

    We required to add protocol inside Objective C file -

    #import "ARBot-Swift.h"
    
    @interface ChatScreenViewController : JSQMessagesViewController <SpeechRecognizerDelegate>
    

    Then you need to conform to the protocol methods -

    - (void)viewDidLoad {
        [super viewDidLoad];
        SpeechRecognizer * speechRecognizer = [[SpeechRecognizer alloc] init];
        speechRecognizer.delegate = self;
    }
    
    
    #pragma mark - Delegate Methods
    -(void)speechRecognitionFinished:(NSString *) transcription{
       //Do something here
    }
    
    -(void)speechRecognitionError:(NSError *) error{
       //Do something here
    }