The Watson Developer Cloud Swift SDK strives to write “Swifty” code that follows the community’s conventions and best practices. Unfortunately, that means our framework does not automatically bridge to Objective-C. We recommend writing a custom bridge in Swift to consume the Swift SDK in an Objective-C application. The following tutorial describes how to build a Swift bridge to consume the Watson Developer Cloud Swift SDK in an Objective-C application.
Create an Objective-C application.
We recommend using the Carthage dependency manager to build the SDK and keep it up-to-date. To use Carthage, create a file called Cartfile
in the root directory of your project with the contents github "watson-developer-cloud/swift-sdk"
and run carthage update --platform iOS
.
$ echo "github \"watson-developer-cloud/swift-sdk\"" > Cartfile
$ carthage update --platform iOS
Add the frameworks you’d like to use to the project, including their dependencies. (All frameworks depend upon Alamofire, Freddy, and RestKit. SpeechToText additionally depends upon Starscream.)
Add a “Copy Frameworks” build phase with the frameworks and dependencies you’d like to use. We’ll use Text to Speech as an example for this tutorial.
Create a WatsonBridge.swift
file. When prompted, allow Xcode to build an Objective-C bridging header.
Import the Swift SDK framework(s) you’d like to use in WatsonBridge.swift
.
We’re going to write a class in WatsonBridge.swift
that can automatically bridge to Objective-C. This class will contain methods that invoke the SDK, process the results, and return any desired values to an Objective-C caller. This class can invoke the SDK because it is written in Swift.
Create a class in WatsonBridge.swift
that inherits from NSObject
(this makes it accessible from Objective-C callers) and write any desired methods.
Import the generated Swift header in your Objective-C file. Since this tutorial app is called ObjectiveCTest
, we import ObjectiveCTest-swift.h
. This header provides access to the classes and methods in WatsonBridge.swift
. Now we can execute methods from WatsonBridge.swift
in our Objective-C code.