swift-sdk

Watson Developer Cloud Swift SDK: Objective-C Compatability

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 Application and Load Dependencies

Create an Objective-C application.

screen shot 2016-09-10 at 11 51 19 pm

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

screen shot 2016-09-10 at 11 54 36 pm

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.)

screen shot 2016-09-11 at 12 21 16 am

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.

screen shot 2016-09-11 at 12 11 49 am

screen shot 2016-09-11 at 12 12 17 am

screen shot 2016-09-11 at 12 13 04 am

Bridge Objective-C to Swift

Create a WatsonBridge.swift file. When prompted, allow Xcode to build an Objective-C bridging header.

screen shot 2016-09-11 at 12 05 26 am

Import the Swift SDK framework(s) you’d like to use in WatsonBridge.swift.

screen shot 2016-09-11 at 12 13 51 am

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.

screen shot 2016-09-11 at 12 17 13 am

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.

screen shot 2016-09-11 at 12 27 43 am