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
SFClass
as a subclass ofNSObject
. - Select
SFClass.h
and make sure its Target Membership isSimpleFramework
and "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
SimpleClass
as a subclass ofNSObject
and add the following code toSimpleClass.swift
. Note the usage ofpublic
in front of the class, the initializer, and theprintMessage
method. 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.h
for you. Add the following to that file:
#import "SFClass.h"
- Create a new single-view iOS app target in the project and name it
SwiftApp
and use Swift. - Select the new target and go to the
General
settings. UnderEmbedded Binaries
, click the+
and addSimpleFramework.framework
. - In the
ViewController.swift
file 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
ObjCApp
and use Objective C. - Select the new target and go to the
General
settings. UnderEmbedded Binaries
, click the+
and addSimpleFramework.framework
. - Under the
Build Settings
for the target, find the setting forEmbedded Content Contains Swift Code
and 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];
}