Quantcast
Channel: iOS – bencoding
Viewing all articles
Browse latest Browse all 41

Adding a Swift Bridge Header manually

$
0
0

Change are if you are using Swift for more then “Hello World” you will need to interact with existing Objective-C libraries such as FMDB, FCModel, MMWormhole, or something similar.  Although Apple has come great documentation and there is a WWDC video discussing this I thought it might be helpful to walk through my experiences as someone new to Swift.

As I do most of my mobile development around the native aspects of the Titanium framework, I thought it would be interesting to explore writing native extensions in both Objective-C and Swift.  So as part of the Ti.Wormhole project, I provided examples in both languages.  Since the MMWormhole project which Ti.Wormhole is based upon is written in Objective-C, a bridging header is required to talk between the Swift extension and the wormhole.

The first step in creating the bridging header is to add a header file to your project.  This is just like adding any other header file, just using the [MyProjectName]-Bridging-Header.h naming contention.  If you haven’t done this before, in Xcode select File –> New –> File… from the menu then select Header File as shown below.

create-h

Then press Next and enter the name of your bridging header. This needs to be done in the [MyProjectName]-Bridging-Header.h, in the following screenshot this is shown as TodaySwift-Bridging-Header to match our extension name.  If you have multiple targets like in the WormholeExample project you will want to select the correct Target or Targets to apply.  I also found that the bridging header likes to be in the root of your project, so would recommend avoiding placing the file in a nested directory.  After verifying your Targets, Naming, and placement, press the Create button to continue.

create-header

You will now have a file with contents similar to the below.  To allow Swift to access your Objective-C libraries you just need to #import the headers for your libraries as shown below with the MMWormholeClient.h.

bridge-header

Next you will need to update your Target’s Build Settings to reference your Bridging Header.  This is done by opening the Building Settings tab in Xcode and scrolling down to the Swift Compiler section.  Here you want to update the Install Objective-C Compatibility Header option to Yes and enter the name of your Bridging Header file into the Objective-C bridging Header option as shown below.

build-setting

You are almost ready to start using your Objective-C libraries from Swift.  The very last thing you need to do is import Foundation at the top of the Swift file you are using to reference Objective-C.  This is demonstrated in the example project Swift file here and illustrated in the screenshot below.

import



Viewing all articles
Browse latest Browse all 41

Trending Articles