413
votes

Xcode 3.2 provides an awesome new feature under the Build menu, "Build and Archive" which generates an .ipa file suitable for Ad Hoc distribution. You can also open the Organizer, go to "Archived Applications," and "Submit Application to iTunesConnect."

Is there a way to use "Build and Archive" from the command line (as part of a build script)? I'd assume that xcodebuild would be involved somehow, but the man page doesn't seem to say anything about this.

UPDATE Michael Grinich requested clarification; here's what exactly you can't do with command-line builds, features you can ONLY do with Xcode's Organizer after you "Build and Archive."

  1. You can click "Share Application..." to share your IPA with beta testers. As Guillaume points out below, due to some Xcode magic, this IPA file does not require a separately distributed .mobileprovision file that beta testers need to install; that's magical. No command-line script can do it. For example, Arrix's script (submitted May 1) does not meet that requirement.
  2. More importantly, after you've beta tested a build, you can click "Submit Application to iTunes Connect" to submit that EXACT same build to Apple, the very binary you tested, without rebuilding it. That's impossible from the command line, because signing the app is part of the build process; you can sign bits for Ad Hoc beta testing OR you can sign them for submission to the App Store, but not both. No IPA built on the command-line can be beta tested on phones and then submitted directly to Apple.

I'd love for someone to come along and prove me wrong: both of these features work great in the Xcode GUI and cannot be replicated from the command line.

20
Aw, crud. This appears to be impossible. If you don't know the answer, please at least vote up the question so my bounty doesn't vanish into the ether... :-(Dan Fabulich
This isn't impossible, it just isn't part of xcodebuild. Creating an IPA file just involves putting the app into a directory named "Payload", zipping that directory, and renaming it to MyAppName.ipa.Michael Grinich
@Michael, "Build and Archive" also enables the Organizer features, which are not available when you just make an IPA file by hand.Dan Fabulich
My comment got a bit long, so it's posted as an answer.Michael Grinich
Although the first/accepted answer by vdaubry will work, the answer by Reid is much simpler for the newer versions of Xcode.Prometheus

20 Answers

320
votes

I found how to automate the build and archive process from the comand line, I just wrote a blog article explaining how you can achieve that.

The command you have to use is xcrun:

/usr/bin/xcrun -sdk iphoneos PackageApplication \
-v "${RELEASE_BUILDDIR}/${APPLICATION_NAME}.app" \
-o "${BUILD_HISTORY_DIR}/${APPLICATION_NAME}.ipa" \
--sign "${DEVELOPER_NAME}" \
--embed "${PROVISONING_PROFILE}"

You will find all the details in the article. If you have any questions dont hesitate to ask.

286
votes

With Xcode 4.2 you can use the -scheme flag to do this:

xcodebuild -scheme <SchemeName> archive

After this command the Archive will show up in the Xcode Organizer.

164
votes

Updating my answer with Xcode 9 and Swift

Archive

xcodebuild -workspace <ProjectName>/<ProjectName>.xcworkspace \
  -scheme <schemeName> clean archive -configuration release \
  -sdk iphoneos -archivePath <ProjectName>.xcarchive

IPA Export (please note the export option plist)

xcodebuild -exportArchive -archivePath  <ProjectName>.xcarchive \
  -exportOptionsPlist  <ProjectName>/exportOptions.plist \
  -exportPath  <ProjectName>.ipa

For those who don't know about exportOptions.plist, https://blog.bitrise.io/new-export-options-plist-in-xcode-9


Those who were using this for building project in CI/CD tools like teamcity/jenkins, please make sure you are using the right xcode installed in the build agent for for both archive and export.

You can use either of below 2 options for this.

  1. Use the full path to xcodebuild,
/Applications/Xcode 9.3.1.app/Contents/Developer/usr/bin/xcodebuild
  1. Use xcode-select,
xcode-select -switch /Applications/Xcode 9.3.1.app

Below is my old answer

Here is command line script for creating archive and IPA example. I have an iPhone xcode project , which is located in Desktop/MyiOSApp folder.

Execute following commands one by one:

cd /Users/username/Desktop/MyiOSApp/

xcodebuild -scheme MyiOSApp archive \
  -archivePath /Users/username/Desktop/MyiOSApp.xcarchive

xcodebuild -exportArchive -exportFormat ipa \
  -archivePath "/Users/username/Desktop/MyiOSApp.xcarchive" \
  -exportPath "/Users/username/Desktop/MyiOSApp.ipa" \
  -exportProvisioningProfile "MyCompany Distribution Profile"

This is tested with Xcode 5 and working fine for me.

29
votes

I've been using my own build script to generate the ipa package for ad hoc distribution.

die() {
    echo "$*" >&2
    exit 1
}

appname='AppName'
config='Ad Hoc Distribution'
sdk='iphoneos3.1.3'
project_dir=$(pwd)

echo using configuration $config

echo updating version number
agvtool bump -all
fullversion="$(agvtool mvers -terse1)($(agvtool vers -terse))"
echo building version $fullversion

xcodebuild -activetarget -configuration "$config" -sdk $sdk build || die "build failed"

echo making ipa...
# packaging
cd build/"$config"-iphoneos || die "no such directory"
rm -rf Payload
rm -f "$appname".*.ipa
mkdir Payload
cp -Rp "$appname.app" Payload/
if [ -f "$project_dir"/iTunesArtwork ] ; then
    cp -f "$project_dir"/iTunesArtwork Payload/iTunesArtwork
fi

ipaname="$appname.$fullversion.$(date -u +%Y%m%d%H%M%S).ipa"
zip -r $ipaname Payload

echo finished making $ipaname

The script also increment the version number. You can remove that part if it's not needed. Hope it helps.

26
votes

The xcodebuild tool can build and export archive products with the -exportArchive flag (as of Xcode 5). The export step was previously only possible via the Xcode Organizer UI.

First archive your app:

xcodebuild -scheme <scheme name> archive

Given $ARCHIVE_PATH (the path to the .xcarchive file), export the app from the archive with one of the following:

iOS .ipa file:

xcodebuild -exportArchive -exportFormat ipa -archivePath "$ARCHIVE_PATH" -exportPath "myApp.ipa" -exportProvisioningProfile "My App Provisioning profile"

Mac .app file:

xcodebuild -exportArchive -exportFormat app -archivePath "$ARCHIVE_PATH" -exportPath "myApp.app" -exportSigningIdentity "Developer ID Application: My Software Company"

In both commands the -exportProvisioningProfile and -exportSigningIdentity arguments are optional. man xcodebuild for details on the semantics. In these examples, the provisioning profile for the iOS build specified an AdHoc distribution provisioning profile, and the signing identity for the Mac app specified a Developer ID for export as a 3rd party application (i.e. not distributed via the Mac App Store).

25
votes

We developed an iPad app with XCode 4.2.1 and wanted to integrate the build into our continuous integration (Jenkins) for OTA distribution. Here's the solution I came up with:

# Unlock keychain
security unlock-keychain -p jenkins /Users/jenkins/Library/Keychains/login.keychain

# Build and sign app
xcodebuild -configuration Distribution clean build

# Set variables
APP_PATH="$PWD/build/Distribution-iphoneos/iPadApp.app"
VERSION=`defaults read $APP_PATH/Info CFBundleShortVersionString`
REVISION=`defaults read $APP_PATH/Info CFBundleVersion`
DATE=`date +"%Y%m%d-%H%M%S"`
ITUNES_LINK="<a href=\"itms-services:\/\/?action=download-manifest\&url=https:\/\/xxx.xxx.xxx\/iPadApp-$VERSION.$REVISION-$DATE.plist\">Download iPad2-App v$VERSION.$REVISION-$DATE<\/a>"

# Package and verify app
xcrun -sdk iphoneos PackageApplication -v build/Distribution-iphoneos/iPadApp.app -o $PWD/iPadApp-$VERSION.$REVISION-$DATE.ipa

# Create plist
cat iPadApp.plist.template | sed -e "s/\${VERSION}/$VERSION/" -e "s/\${DATE}/$DATE/" -e "s/\${REVISION}/$REVISION/" > iPadApp-$VERSION.$REVISION-$DATE.plist

# Update index.html
curl https://xxx.xxx.xxx/index.html -o index.html.$DATE
cat index.html.$DATE | sed -n '1h;1!H;${;g;s/\(<h3>Aktuelle Version<\/h3>\)\(.*\)\(<h3>&Auml;ltere Versionen<\/h3>.<ul>.<li>\)/\1\
${ITUNES_LINK}\
\3\2<\/li>\
<li>/g;p;}' | sed -e "s/\${ITUNES_LINK}/$ITUNES_LINK/" > index.html

Then Jenkins uploads the ipa, plist and html files to our webserver.

This is the plist template:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>items</key>
    <array>
        <dict>
            <key>assets</key>
            <array>
                <dict>
                    <key>kind</key>
                    <string>software-package</string>
                    <key>url</key>
                    <string>https://xxx.xxx.xxx/iPadApp-${VERSION}.${REVISION}-${DATE}.ipa</string>
                </dict>
                <dict>
                    <key>kind</key>
                    <string>full-size-image</string>
                    <key>needs-shine</key>
                    <true/>
                    <key>url</key>
                    <string>https://xxx.xxx.xxx/iPadApp.png</string>
                </dict>
                <dict>
                    <key>kind</key>
                    <string>display-image</string>
                    <key>needs-shine</key>
                    <true/>
                    <key>url</key>
                    <string>https://xxx.xxx.xxx/iPadApp_sm.png</string>
                </dict>
            </array>
            <key>metadata</key>
            <dict>
                <key>bundle-identifier</key>
                <string>xxx.xxx.xxx.iPadApp</string>
                <key>bundle-version</key>
                <string>${VERSION}</string>
                <key>kind</key>
                <string>software</string>
                <key>subtitle</key>
                <string>iPad2-App</string>
                <key>title</key>
                <string>iPadApp</string>
            </dict>
        </dict>
    </array>
</dict>
</plist>

To set this up, you have to import the distribution certificate and provisioning profile into the designated user's keychain.

16
votes

I found some of the other answers here hard to get going. This article did if for me. Some paths may need to be absolute, as mentioned in the other answers.

The Command:

xcrun -sdk iphoneos PackageApplication \
    "/path/to/build/MyApp.app" \
    -o "output/path/to/MyApp.ipa" \
    --sign "iPhone Distribution: My Company" \
    --embed "/path/to/something.mobileprovision"
15
votes

You CAN actually resign a build, just as XCode does, so that you can test and ship the same binary. For example in my script (similar to those above) I build my release version signed as an AdHoc build, then I archive that as an IPA for testing, then resign with my distribution cert and create a zip file, which is what I send to Apple. The relevant line is:

codesign -f -vv -s "$DistributionIdentity" "$APPDIR"
14
votes

For Xcode 7, you have a much simpler solution. The only extra work is that you have to create a configuration plist file for exporting archive.

(Compared to Xcode 6, in the results of xcrun xcodebuild -help, -exportFormat and -exportProvisioningProfile options are not mentioned any more; the former is deleted, and the latter is superseded by -exportOptionsPlist.)

Step 1, change directory to the folder including .xcodeproject or .xcworkspace file.

cd MyProjectFolder

Step 2, use Xcode or /usr/libexec/PlistBuddy exportOptions.plist to create export options plist file. By the way, xcrun xcodebuild -help will tell you what keys you have to insert to the plist file.

Step 3, create .xcarchive file (folder, in fact) as follows(build/ directory will be automatically created by Xcode right now),

xcrun xcodebuild -scheme MyApp -configuration Release archive -archivePath build/MyApp.xcarchive

Step 4, export as .ipa file like this, which differs from Xcode6

xcrun xcodebuild -exportArchive -exportPath build/ -archivePath build/MyApp.xcarchive/ -exportOptionsPlist exportOptions.plist

Now, you get an ipa file in build/ directory. Just send it to apple App Store.

By the way, the ipa file created by Xcode 7 is much larger than by Xcode 6.

14
votes

I have given a brief description of steps to follow, and parameters to pass while generating an ipa using terrminal below:

  1. Go to the folder which contains the MyApp.xcodeproject file in terminal

  2. By using the command given below you will get all the Targets of the application

    /usr/bin/xcodebuild -list 
    
  3. After the above command is executed, you will get a list of targets of which you should select a specific target you need to generate .ipa

    /usr/bin/xcodebuild -target $TARGET -sdk iphoneos -configuration Release
    
  4. The above command builds the project and creates a .app file.The path to locate the .app file is ./build/Release-iphoneos/MyApp.app

  5. After Build gets succeeded then execute the following command to generate .ipa of the application using Developer Name and Provisioning Profile using the syntax below:

    /usr/bin/xcrun -sdk iphoneos PackageApplication -v “${TARGET}.app” -o “${OUTDIR}/${TARGET}.ipa” –sign “${IDENTITY}” –embed “${PROVISONING_PROFILE}”
    

Explanation of each Parameter in the above syntax:

${TARGET}.app                == Target path (ex :/Users/XXXXXX/desktop/Application/build/Release-iphoneos/MyApp.app)
${OUTDIR}                    == Select the output directory(Where you want to save .ipa file)
${IDENTITY}                   == iPhone Developer: XXXXXXX (XXXXXXXXXX)(which can be obtained from Keychain access)
${PROVISONING_PROFILE}   == Path to the provisioning profile(/Users/XXXXXX/Library/MobileDevice/Provisioning Profiles/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX.mobileprovision”)
  1. ipa will be generated at selected output directory "${OUTDIR}"
8
votes

Xcode 8:


IPA Format:

xcodebuild -exportArchive -exportFormat IPA -archivePath MyMobileApp.xcarchive -exportPath MyMobileApp.ipa -exportProvisioningProfile 'MyMobileApp Distribution Profile'

Exports the archive MyMobileApp.xcarchive as an IPA file to the path MyMobileApp.ipa using the provisioning profile MyMobileApp Distribution Profile.

APP Format:

xcodebuild -exportArchive -exportFormat APP -archivePath MyMacApp.xcarchive -exportPath MyMacApp.pkg -exportSigningIdentity 'Developer ID Application: My Team'

Exports the archive MyMacApp.xcarchive as a PKG file to the path MyMacApp.pkg using the appli-cation application cation signing identity Developer ID Application: My Team. The installer signing identity Developer ID Installer: My Team is implicitly used to sign the exported package.

Xcodebuild man page

7
votes

Go to the folder where's your project root and:

xcodebuild -project projectname -activetarget -activeconfiguration archive
4
votes

Going one step further, uploading to iTunesConnect via commandline with Xcode 7! (Assuming you are starting with an .ipa that has been signed with the correct release profile and signing identity.)

Enter altool, the CLI interface for the Application Loader (docs, page 38). Hidden deep within Xcode.app's structure, is a handy function to let us upload directly to ItunesConnect.

/Applications/Xcode.app/Contents/Applications/Application Loader.app/Contents/Frameworks/ITunesSoftwareService.framework/Versions/A/Support/altool

Simply run $ altool --upload-app -f file -u username [-p password] to upload your newly minted .ipa straight to Apple. The password is optional, and will prompt you for it if you leave it off the command.

If there are any issues with the app during the verification step, the console will print them out.

You will likely have to export the path to altool if you don't want to save its location.

export PATH=$PATH:/Applications/Xcode.app/Contents/Applications/Application\ Loader.app/Contents/Frameworks/ITunesSoftwareService.framework/Versions/A/Support/

Thats it! Simply login to iTunesConnect.com and select your new build for testing with testflight.

Final Note: If you get an error saying Exception while launching iTunesTransporter: Transporter not found at path: /usr/local/itms/bin/iTMSTransporter. You should reinstall the application, you can follow the suggestion on this SO answer, to run a symlink to the correct location:

ln -s /Applications/Xcode.app/Contents/Applications/Application\ Loader.app/Contents/itms /usr/local/itms
4
votes

How to build iOS project with command?

Clean : codebuild clean -workspace work-space-name.xcworkspace -scheme scheme-name 

&&

Archive : xcodebuild archive -workspace work-space-name.xcworkspace -scheme "scheme-name" -configuration Release -archivePath IPA-name.xcarchive 

&&

Export : xcodebuild -exportArchive -archivePath IPA-name.xcarchive -exportPath IPA-name.ipa -exportOptionsPlist exportOptions.plist


What is ExportOptions.plist?

ExportOptions.plist is required in Xcode . It lets you to specify some options when you create an ipa file. You can select the options in a friendly UI when you use Xcode to archive your app.

Important: Method for release and development is different in ExportOptions.plist

AppStore :

exportOptions_release ~ method = app-store

Development

exportOptions_dev ~ method = development

3
votes

Improving on Vincent's answer, I wrote a script to do that: xcodearchive
It allows you to archive (generate an ipa) your project via the command line. Think of it like the sister of the xcodebuild command, but for archiving.

Code is available on github: http://github.com/gcerquant/xcodearchive


One option of the script is to enable the archiving of the dSYM symbols in a timestamped archive. No excuse to not keep the symbols anymore, and not be able to symbolicate the crash log you might later receive.

2
votes

try xctool, it is a replacement for Apple's xcodebuild that makes it easier to build and test iOS and Mac products. It's especially helpful for continuous integration. It has a few extra features:

  1. Runs the same tests as Xcode.app.
  2. Structured output of build and test results.
  3. Human-friendly, ANSI-colored output.

No.3 is extremely useful. I don't if anyone can read the console output of xcodebuild, I can't, usually it gave me one line with 5000+ characters. Even harder to read than a thesis paper.

xctool: https://github.com/facebook/xctool

2
votes

if you use next tool: https://github.com/nomad/shenzhen

then this task is very easy:

which ipa 1>/dev/null 2>&1 || echo 'no shenzhen. to install use: sudo gem install shenzhen --no-ri --no-rdoc'
ipa build --verbose --scheme "${schemeName}"

source

2
votes

After updating to Xcode 8, I found that enterprise ipa generate by

/usr/bin/xcrun -sdk iphoneos PackageApplication -v "${RELEASE_BUILDDIR}/${APPLICATION_NAME}.app" -o "${BUILD_HISTORY_DIR}/${APPLICATION_NAME}.ipa" --sign "${DEVELOPER_NAME}" --embed "${PROVISONING_PROFILE}" 

Command cannot be launched because of some signature issue. The log indicates that "warning: PackageApplication is deprecated, use xcodebuild -exportArchive instead.

So I switch to xcodebuild -exportArchive and everything went back normal.

1
votes

You mean the validate/share/submit options? I think those are specific to Xcode, and not suited for a command-line build tool.

With some cleverness, I bet you could make a script to do it for you. It looks like they're just stored in ~/Library/MobileDevice/Archived Applications/ with a UUDI and a plist. I can't imagine it would be that hard to reverse engineer the validator either.

The process I'm interested automating is sending builds to beta testers. (Since App Store submission happens infrequently, I don't mind doing it manually, especially since I often need to add new description text.) By doing a pseudo Build+Archive using Xcode's CLI, I can trigger automatic builds from every code commit, create IPA files with embedded provisioning profiles, and email it to testers.

1
votes

Open Terminal & drag and drop your project folder:

cd /Users/username/Desktop/demo/

Execute the following commands one by one:

Builds app as-"demo.xcodeproj" into an archive

xcodebuild archive -project demo.xcodeproj -scheme demo -archivePath /Users/username/Desktop/demo.xcarchive

If your app has Podfile fie as-"demo.xcworkspace"-

xcodebuild -workspace Project-Name.xcworkspace -scheme Scheme-Name -sdk iphoneos -configuration Release Provisioning_Profile=“Provision-Name” Development_Team=“Team-ID” archive -archivePath /Path/To/Output/AppName.xcarchive archive

IPA Export Build Command

Download ExportOptions.plist file from Here

xcodebuild -exportArchive -archivePath /Users/shilpa/Desktop/demo.xcarchive -exportPath /Users/shilpa/Desktop/demo.ipa -exportOptionsPlist /Users/shilpa/Downloads/ExportOptions.plist