在基于Cordova的Xcode项目

时间:2017-06-05 14:43:14

标签: ios xcode cordova

我有一个基于Cordova的iOS项目,我需要在构建阶段添加自定义脚本。我有一个设置,它工作正常,但我需要能够以某种方式自动添加构建阶段,因为我需要项目能够在CI服务器上自动安装和构建,而无需手动添加阶段xcode中。

为了澄清,当cordova platform add ios运行时,项目是在没有构建阶段的情况下创建的,我需要在cordova build ios之前(或期间)以编程方式添加构建阶段。

我可以在.xcconfig文件中添加自定义构建设置,是否可以在某处定义构建阶段?我看到构建阶段存在于我的.pbxproj文件中,但是这是自动生成的,并且包含一些随机ID,所以我不确定它可以解析并插入任意内容吗?

2 个答案:

答案 0 :(得分:3)

我发现的解决方案是使用Xcode项目解析器,周围有几个。我使用过cordova-node-xcode。我无法找到任何API文档,但单元测试有助于弄清楚我需要什么。我需要使用proj.addBuildPhase方法,可以在此处看到使用此方法添加运行脚本的示例:https://github.com/apache/cordova-node-xcode/blob/master/test/addBuildPhase.js#L113

答案 1 :(得分:0)

基于一个可接受的答案,我创建了代码,也许有人可以使用它:)

使用以下命令安装xcode npm:

npm i xcode

在根目录中创建extend_build_phase.js:

var xcode = require('xcode');
var fs = require('fs');
var path = require('path');

const xcodeProjPath = fromDir('platforms/ios', '.xcodeproj', false);
const projectPath = xcodeProjPath + '/project.pbxproj';
const myProj = xcode.project(projectPath);
// Here you can add your own shellScript
var options = { shellPath: '/bin/sh', shellScript: 'echo "hello world!"' };

myProj.parse(function(err) {
  myProj.addBuildPhase([], 'PBXShellScriptBuildPhase', 'Run a script',myProj.getFirstTarget().uuid, options);
  fs.writeFileSync(projectPath, myProj.writeSync());
})

function fromDir(startPath, filter, rec, multiple) {
  if (!fs.existsSync(startPath)) {
    console.log("no dir ", startPath);
    return;
  }
  const files = fs.readdirSync(startPath);
  var resultFiles = [];
  for (var i = 0; i < files.length; i++) {
    var filename = path.join(startPath, files[i]);
    var stat = fs.lstatSync(filename);
    if (stat.isDirectory() && rec) {
      fromDir(filename, filter); //recurse
    }

    if (filename.indexOf(filter) >= 0) {
      if (multiple) {
        resultFiles.push(filename);
      } else {
        return filename;
      }
    }
  }
  if (multiple) {
    return resultFiles;
  }
}

使用以下代码扩展config.xml:

<platform name="ios">
    ...
    <hook src="extend_build_phase.js" type="after_platform_add" />
    ...
</platform>

我创建了一个Ionic项目,因此要使其正常运行,请使用以下命令:

ionic cordova platform rm ios
ionic cordova platform add ios
ionic cordova build ios