From 9ef33c6527f6f93d0986db548f866ebbac99ca72 Mon Sep 17 00:00:00 2001 From: Marian Hello Date: Fri, 17 Jun 2016 18:07:58 +0200 Subject: [PATCH] enable imports of swift code into objc #9 --- README.md | 13 +++++++++++++ src/main.js | 29 +++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/README.md b/README.md index e6b8270..b3185d8 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,19 @@ As an example you can have a look at this [plugin](https://github.com/akofman/co If the `cordova-plugin-add-swift-support` plugin is already installed to your project, then you can add your own Swift plugin as usual, its prefixed Bridging-Header will be automatically found and merged. +## Importing Swift into ObjectiveC code + +Because **ProductModuleName** of application using some Swift Cordova plugin is different than **ProductModuleName** of the +plugin itself, you need to modify your ***.m*** files imports to: + +``` +#import "Swift2Objc-Header.h" +``` + +\* instead of ~~#import "ProductModuleName-Swift.h"~~ + +This header will be created by this plugin and automatically registered with xcode project. + ## Contributing The src folder contains ECMAScript 2015 source files. diff --git a/src/main.js b/src/main.js index b4859a1..be90b1d 100644 --- a/src/main.js +++ b/src/main.js @@ -36,6 +36,8 @@ export default (context) => { let bridgingHeaderPath; let bridgingHeaderContent; + let swift2objHeaderPath; + let swift2objcHeaderContent; let projectName; let projectPath; let pluginsPath; @@ -81,6 +83,21 @@ export default (context) => { xcodeProject.addHeaderFile('Bridging-Header.h'); } + swift2objHeaderPath = getSwift2ObjcHeaderPath(context, projectPath, iosPlatformVersion); + + try{ + fs.statSync(swift2objHeaderPath); + } catch(err) { + // If the bridging header doesn't exist, we create it with the minimum + // ProductModuleName-Swift.h import. + swift2objcHeaderContent = [ '//', + '// Use this file to import your projects\'s generated swift-header to expose Swift to Objective-C.', + '//', + '#import "' + projectName.replace(' ', '_') + '-Swift.h"' ]; + fs.writeFileSync(swift2objHeaderPath, swift2objcHeaderContent.join('\n'), { encoding: 'utf-8', flag: 'w' }); + xcodeProject.addHeaderFile('Swift2Objc-Header.h'); + } + buildConfigs = xcodeProject.pbxXCBuildConfigurationSection(); const bridgingHeaderProperty = '"$(PROJECT_DIR)/$(PROJECT_NAME)' + bridgingHeaderPath.split(projectPath)[1] + '"'; @@ -186,3 +203,15 @@ const getBridgingHeaderPath = (context, projectPath, iosPlatformVersion) => { return bridgingHeaderPath; }; + +const getSwift2ObjcHeaderPath = (context, projectPath, iosPlatformVersion) => { + const semver = context.requireCordovaModule('semver'); + let headerPath; + if(semver.lt(iosPlatformVersion, '4.0.0')) { + headerPath = path.posix.join(projectPath, 'Plugins', 'Swift2Objc-Header.h'); + } else { + headerPath = path.posix.join(projectPath, 'Swift2Objc-Header.h'); + } + + return headerPath; +} \ No newline at end of file