The purpose of this project is to demonstrate (and remember) how to create a Swift framework for iOS that in turn uses Objective-C code. Then, this framework is used by two different iOS apps -- one Swift and one Objective-C.
- Create a new Xcode project.
- Create a new Cocoa Touch framework target using Swift.
- Create a new Objective C Cocoa Touch class named
SFClassas a subclass ofNSObject. - Select
SFClass.hand make sure its Target Membership isSimpleFrameworkand "Public". Turns out this is critical. - Add the following code to
SFClass.h:
-(void) printMessage:(NSString *) message;
- Add the following code to
SFClass.m:
-(void) printMessage:(NSString *) message {
NSLog(@"The message is %@", message);
}
- Create a new Swift class named
SimpleClassas a subclass ofNSObjectand add the following code toSimpleClass.swift. Note the usage ofpublicin front of the class, the initializer, and theprintMessagemethod. This makes the class and methods available to those who consume the framework.
public class SimpleClass: NSObject {
var message: String
var object: SFClass = SFClass()
public init(_ newMessage: String) {
self.message = newMessage
}
public func printMessage() {
object.printMessage(self.message)
}
}
- When you created the framework target, Xcode automatically created
SimpleFramework.hfor you. Add the following to that file:
#import "SFClass.h"
- Create a new single-view iOS app target in the project and name it
SwiftAppand use Swift. - Select the new target and go to the
Generalsettings. UnderEmbedded Binaries, click the+and addSimpleFramework.framework. - In the
ViewController.swiftfile that was created, add the following line at the top:
import SimpleFramework
and the following method should replace the existing viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
let sc = SimpleClass("Hello Swift framework from Swift!!!")
sc.printMessage()
}
- Create a new single-view iOS app target in the project and name it
ObjCAppand use Objective C. - Select the new target and go to the
Generalsettings. UnderEmbedded Binaries, click the+and addSimpleFramework.framework. - Under the
Build Settingsfor the target, find the setting forEmbedded Content Contains Swift Codeand set it toYes. - In the ViewController.m file that was created, add the following line at the top:
@import SimpleFramework;
and the following method should replace the existing viewDidLoad:
- (void)viewDidLoad {
[super viewDidLoad];
SimpleClass *sc = [[SimpleClass alloc] init:@"Hello Swift framework from Objective C!!!"];
[sc printMessage];
}