Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling swift from obj c

Tags:

ios

swift

I am trying to call a function in a swift file from objC. I have tried to "#import project_name-Swift.h" but I get an error -> "project_name.h file not found"

The objC file is part of a pod. I don't know if that plays a part in the problem.

Thanks for any help! :)

like image 251
Sam Avatar asked Jan 30 '26 21:01

Sam


2 Answers

You need to follow simple below steps to solved out your problem :

1.) first remove your existing bridging header file from project (select file -> right click -> show in finder).

2.) once you delete, then also check its exist in project or not. if not exist, then prepare new header file at root of your project.

3.) Now select your project and go in build settings. finf swift compiler - code generation section.

enter image description here

4.) set install Objective-C compatibility header to YES

5.) set path in objective-c bridging header like : projectname/bridging-header-filename.h

6.) now by pressing alt key choose product menu and select clean build folder. Run your project and now its worked well..!

like image 134
Pavan Gandhi Avatar answered Feb 02 '26 13:02

Pavan Gandhi


You need to add a bridge header file (PROJECT_NAME-Bridging-Header.h) and add the required headers that XCode can't find in there. You can find the name of that file in the Project's Build Settings under Objective-C Bridging Header.

This file is auto-magically created when you add an objc file to your Swift project and it is used to call from Swift to Objective-C but apparently, it is needed for the opposite direction too.

The other things you will need to do is add a #import "PROJECT_NAME-Swift.h"to your objective-c files. This file is created deep inside the DerivedData project's Build directory and its naming convention is predefined.

Additionally, you will need to extend Swift classes with : NSObject and mark them with @objc at the beginning of the declaration.

Finally, you will need to mark your classes and methods in Swift as public if they are part of a different module. Public is not the default access right.

like image 28
John Difool Avatar answered Feb 02 '26 14:02

John Difool



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!