Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Objective-C CocoaPods in a Swift Project

Is there a way I can use a CocoaPod written in Objective-C in my Swift project using swift?

Do I just make a bridging header? And if so, can I access the objects, classes, and fields defined by the libraries in the CocoaPod in Swift?

like image 831
shaydawg Avatar asked Aug 07 '15 18:08

shaydawg


People also ask

How do I use Objective-C pod in Swift?

Support Objective-C pods in a Swift project First, create your Podfile and add the pods you need as usual. Install them using the pod install command and open the . xcworkspace file created in your project folder. Pods should now be included in your workspace.

Can I use Objective-C in Swift?

You can use Objective-C and Swift files together in a single project, no matter which language the project used originally. This makes creating mixed-language app and framework targets as straightforward as creating an app or framework target written in a single language.


2 Answers

Basic answer to your question is Yes, you can use objective-c code built with CocoaPods.

More important question is "How to use such libs?"
Answer on this question depends on use_frameworks! flag in your Podfile:
Let's imagine that you want use Objective-C pod with name CoolObjectiveCLib.

If your pod file uses use_frameworks! flag:

// Podfile
use_frameworks!
pod 'CoolObjectiveCLib'

Then you don't need add any bridge header files.
Everything that you need is import framework in Swift source file:

// MyClass.swift
import CoolObjectiveCLib

Now you can use all classes that are presented in lib.

If your pod file doesn't use use_frameworks! flag:

// Podfile
pod 'CoolObjectiveCLib'

Then you need create bridging header file and import there all necessary Objective-C headers:

// MyApp-Bridging-Header
#import "CoolObjectiveCLib.h"

Now you can use all classes that are defined in imported headers.

like image 74
Vlad Papko Avatar answered Oct 14 '22 10:10

Vlad Papko


In podFile use the flag use_frameworks! Inside Xcode in the Pod folder structure in the dependency, you add xxxxxxx-umbrella.h in Support Files.

In your {PROJECT_NAME}-Bridging-Header.h use:

#import "xxxxxxx/xxxxxxx-umbrella.h"

It works for me.

like image 42
RodolfoNeto Avatar answered Oct 14 '22 10:10

RodolfoNeto