shaydawg shaydawg - 6 months ago 17
Swift Question

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?

There are a lot of good CocoaPods out there written in Objective C. I only know Swift, and I'm wondering if there's a way for me to still use those CocoaPods.

Answer

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.