如何在一个快速项目中使用 Objective-C CocoPods

在我的 Swift 项目中,有没有一种方法可以使用用 Objective-C 编写的 CocoaPod 来使用 Swift?

我只是做了一个桥头吗?如果是的话,我可以访问 Swift 中 CocoaPod 库定义的对象、类和字段吗?

35867 次浏览

You just need a bridging header and import there what you need.

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.

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.

AND don't forget to add Bridging Header file name to Target -> Build Settings -> Objective-C Bridging Header