Using Objective-C code in iOS Cocoa Static Library

2019-04-13 00:03发布

I am looking for a simple procedure for combining an Objective-C code from a shared library project with Swift code from an application project but have had no success so far with this sequence:

  1. start Xcode 6.1.1
  2. create workspace Test
  3. create iOS Cocoa Touch Static Library project TestLibrary and add it to workspace
  4. create iOS Single View Application project Test (language: Swift) and add it to workspace
  5. add import TestLibrary to ViewController.swift

If I now build Test, I receive this error in ViewController.swift: No such module: ‘TestLibrary’.

Presumably two hurdles must be overcome:

  1. Tell TestLibrary that is should "export" TestLibrary.h. What is the right syntax and procedure for adding the (presumably) required bridging header file?
  2. Tell Test where TestLibrary is located. Since both the application and static library projects belong to the same workspace (and sit in the file system next to each other) I assume no explicit steps are required, or are there?

So in summary, my question is this: how can I overcome the build error even if I subsequently add let test = TestLibrary() to ViewController.swift, i.e. how can Test (Swift code base) make use of TestLibrary (Objective-C code base)?

2条回答
狗以群分
2楼-- · 2019-04-13 00:31

This procedure seems to work (for single app target):

  1. Do not add import TestLibrary, since both the Swift and Objective-C code will reside in the same app target
  2. Create Test-Bridging-Header.h to Test and add #import "TestLibrary/TestLibrary.h"
  3. Set build setting Objective-C Bridging Header: Test/Test-Bridging-Header.h for Test
  4. Drag libTestLibrary.a from TestLibrary (under Products) into Test's Link Library With Binaries (under Build Phases)
  5. Add let test = TestLibrary() e.g. inside viewDidLoadin ViewController.swift

Voila ...

查看更多
不美不萌又怎样
3楼-- · 2019-04-13 00:36

In my case, I have to add all the .h file's of the Framework in the Bridging file, that fixed the issue. Also remove the import TestLibrary from the swift files

查看更多
登录 后发表回答