Don't wanna be here? Send us removal request.
Text
Using Objective-C libraries in Swift with CocoaPods
Hi there!
I have been developing iOS apps for some time now and I would like to say that CocoaPods has been a good friend to handle library dependencies in Xcode projects. However, since Swift came out some developers have had some doubts about how to make use of Objective-C libraries in Swift, since the majority on the market are still in Objective-C.
This tutorial will assume that you are already familiar with CocoaPods. If this is not the case please click here to find more information.
So lets start!
First, lets open Xcode and create an empty application called Example, making sure that language is Swift. Once created, the Project Navigator inside Xcode should look like this:
Second, lets create an empty file that it is going to be called Podfile.
Third, inside the recently created Podfile lets go and list the project libraries dependencies. As an example we are going to be using the MBProgressHUD library, which is simple and very handy when we need to let users know that some work is being done in the background.
platform :ios, '8.0'
pod 'MBProgressHUD' , '~> 0.8'
Fourth, lets open terminal and run the following command in the Podfile path:
$ pod install
Once everything is installed, there should be a new file in your Xcode project path with the same name of the project but with the extension .xcworkspace. So lets go and open this file running the following command.
$ open Example.xcworkspace
Now the Project Navigator should look like this:
This is great! We have the Xcode project with a Swift class and an Objective-C library. However, there are still some missing steps. In order to use the MBProgressHUD library we would need to create a header file that will be used as a bridge between Objective-C and Swift. So lets create the header file following this format <#PROJECT_NAME>-Bridging-Header.h.
Perfect. We are almost done! Now we need to tell Xcode that Example-Bridging-Header.h is going to be the bridge file. In order to do so, lets go to the Build Settings section of our Target and lets click the options all located at the top left corner of the Build Settings view.
Then lets look for the section Swift Compiler – Code Generation and add the recently created bridging header in the option that says Objective-C Bridging Header, using the following format <#PROJECT_NAME>/<#PROJECT_NAME>-Bridging-Header.h, always making sure that the option Install Objective-C Compatibility Header above it is set to Yes.
Excellent, we have set everything that is needed to start using the Objective-C library in a Swift class.
The last step will be to include the MBProgressHUD header in our Example-Bridging-Header.h.
#import "MBProgressHUD.h"
Congratulations! Now we can use MBProgressHUD in any class that needs it!
var hud: MBProgressHUD = MBProgressHUD( )
Hope you find this as useful as I did.
Have a good one!
2 notes
·
View notes