Using Objective-C libraries in Swift

Swift and Objective-C in the Same Project

Jonathan Hdez

2 minute read

In this post I’m going to write how you can use Objective-c libraries in your Swift project.

Xcode projects can contain either language, you can use this feature called Mix and Match to implement the latest swift features in your existing Objective-C proyect, or use objective-c code in new swift apps.

For this example, I’m going to import ProgressHUD library, a lightweight and easy-to-use HUD for iOS. (Objective-C)

1. Clone or Download ProgressHUD from Github.

"Download ProgressHUD"

In Objective-C, there are .m and .h files. A .m file, is where methods are implemented, and the .h file is for public declarations of your class like an API.

2. Copy the .bundle, .h and .m files into your project and the next alert will appear.

"Copy files into your proyect"

Check your project Target, and press Finish.

3. Xcode offers to configure a Bridging header, select option Create bridging header.

"Configure header alert"

4. Now, you can see your Bridging header file in the Navigator

"BrdgingHeader file in navigator"

5. Click on your Bridging header to open, add all your headers files (.h) that you would like to expose to Swift. In my case, I’m going to import the ProgressHUD.h file.

"Import header"

6. Build your project (cmd+B). Now you can use your Objective-C library in your Swift app.

"Use library"

If the option to create Bridging Header automatically has been denied, there’s still an option to create this file manually.

1. Create a new Header File

"Create File"

"Select Header file"

2. Click on your new Bridging header file to open, remove the default text and add all your headers files (.h) that you would like to expose to Swift.

"Import Targets"

3. Now, you need to set the path to the new Bridging Header file in your project Build Settings.

To set the path to your Bridging Header file you need to navigate to your project Build Settings where look for Swift Compiler – General section.

"Build Settings"

4. Double click on Objective-C Bridging Header option to open the Editor.

"Open Editor"

Set the path to your Bridging Header file.

"Set Header Path"

5. Build your project (cmd+B). Now you can use the Objective-C classes in your Swift project.

"Set Header Path"

If you want to directly play with the code, I have added the example code on Github repository.

References

Developer Apple

comments powered by Disqus