Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/3158.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
When running an Android app, the device or emulator to use (including the name of a new emulator) is now selected before the app is built, rather than after.
1 change: 1 addition & 0 deletions changes/860.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
iOS apps can now be run on a physical iOS device. When selecting a device with `-d`/`--device`, connected devices are offered under a "Physical devices" option alongside the simulator iOS versions, and they can also be selected by name or UDID.
1 change: 1 addition & 0 deletions docs/en/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
- [How to run Briefcase](how-to/run.md)
- Obtaining a Code Signing identity
- [Android](how-to/code-signing/android.md)
- [iOS](how-to/code-signing/iOS.md)
- [Linux](how-to/code-signing/linux.md)
- [macOS](how-to/code-signing/macOS.md)
- [Windows](how-to/code-signing/windows.md)
Expand Down
75 changes: 75 additions & 0 deletions docs/en/how-to/code-signing/iOS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# iOS { #code-signing-ios }

## Overview

To run an app on a physical iPhone or iPad, the app must be signed with a development certificate, and installed with a provisioning profile that authorizes it to run on that device. Briefcase uses Xcode to manage provisioning profiles for you, but you need to set up a development certificate, and prepare your device, before you can deploy to it.

You don't need to be a member of the Apple Developer Program to deploy to your own device; a free Apple ID is sufficient. Apple Developer Program membership is only required to distribute your app through the App Store or TestFlight.

These steps only need to be completed once for each Mac and device that you use.

## Requirements

* A Mac with Xcode installed.
* An iPhone or iPad running iOS or iPadOS 17 or later. Briefcase deploys apps using `devicectl`, which doesn't support earlier versions. This only affects the devices you deploy to during development; it doesn't change the minimum iOS version supported by your app.

## Add your Apple ID to Xcode

Open Xcode, then open Xcode's Settings, and select the *Accounts* tab (*Apple Accounts* in Xcode 27 and later). Click the `+` button, select *Apple ID*, and sign in.

If you have a free Apple ID, Xcode creates a *Personal Team* for you. If you're a member of one or more Apple Developer Program teams, each of those teams will also be listed.

## Create a development certificate

In the same tab, select your Apple ID, select the team you want to use, and click *Manage Certificates...*. Click the `+` button, and select *Apple Development*.

This creates an "Apple Development" certificate, and installs it (with its private key) in your login keychain. You can confirm that the certificate is available by running:

```console
$ security find-identity -v -p codesigning
1) 38EBD6F8903EC63C238B04C1067833814CE47CA3 "Apple Development: jane@example.com (A1B2C3D4E5)"
1 valid identities found
```

The 40-character hex string is the identity's fingerprint. You can pass either the fingerprint or the full name of the identity (the part in quotes) to Briefcase using `-i`/`--identity`.

The identifier in parentheses at the end of the name identifies *you*, not your team. Briefcase reads the team from the certificate itself.

## Prepare your device

1. Connect your device to your Mac with a cable, and unlock it. When the device asks if you want to trust the computer, tap *Trust*, and enter your device passcode. After the device has been paired, you can also deploy to it over the local network, as long as the device is on the same network as your Mac.
2. Enable Developer Mode on the device. Open *Settings > Privacy & Security > Developer Mode*, and turn on Developer Mode. The device will restart; when it has restarted, confirm that you want to turn on Developer Mode. If the Developer Mode option isn't visible, open Xcode's *Window > Devices and Simulators* window while the device is connected; this will make the option appear.

You can confirm that the device is ready by running:

```console
$ xcrun devicectl list devices
```

The device should be listed with a state of `available (paired)`.

## Deploy your app

You can now run your app on the device:

```console
$ briefcase run iOS -d
```

Select *Physical devices* from the list, then select your device. Briefcase will ask you to select a development signing identity, then build the app, install it on the device, and start it. If the device isn't ready to run apps (for example, because Developer Mode isn't enabled), it will be labeled with the reason; if you select it, Briefcase will describe how to fix the problem.

The first time you run an app signed with a free Apple ID's certificate, iOS won't start the app, and Briefcase will report that the profile "has not been explicitly trusted by the user". To trust your certificate, open *Settings > General > VPN & Device Management* on the device, select your Apple ID under *Developer App*, and tap *Trust*. Then run your app again. You only need to do this once for each certificate.

## Signing behavior

Briefcase uses Xcode's automatic signing. The signing identity you select determines the team that is used; Xcode then creates or updates the provisioning profile for your app and device, registers the device with the team if necessary, and signs the app with that team's development certificate. If you have more than one development certificate for the same team in your keychain, Xcode selects which one is used.

Each app is identified by its bundle identifier (the [`bundle`][] and app name in your `pyproject.toml`). Bundle identifiers must be unique across *all* Apple developer teams, so you can't use a bundle identifier that has been registered by someone else. If Xcode reports that it can't register your bundle identifier, use a bundle based on a domain that you control.

### Free Apple ID limitations

Apps signed with a free Apple ID have some limitations:

* Provisioning profiles expire after 7 days. After that, the app won't start. Rebuilding the app with `briefcase build iOS -d` will renew the profile.
* You can only register a small number of new bundle identifiers each week, and only a small number of apps signed with a free Apple ID can be installed on a device at the same time.
* Some capabilities (such as push notifications and iCloud) aren't available.
54 changes: 43 additions & 11 deletions docs/en/reference/platforms/iOS/xcode.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,27 @@ iOS allows for some customization of the colors used by your app:

The following options can be provided at the command line when producing iOS projects:

### build

#### `-d [<device>]` / `--device [<device>]`

The device to build for. Accepts the same values, and has the same default, as the `-d`/`--device` option for `run`. If a physical device is selected, the app will be built and signed for that device.

#### `-i <identity>` / `--identity <identity>`

The development signing identity to use when building for a physical device. Accepts the same values as the `-i`/`--identity` option for `run`.

### run

#### `-d [<device>]` / `--device [<device>]`

The device simulator to target. Can be either a UDID, a device name (e.g., `"iPhone 11"`), a device name and OS version (`"iPhone 11::iOS 13.3"`), or `auto`. `auto` is the default behavior; Briefcase will automatically select an "entry level" iPhone simulator (e.g., an iPhone SE, or iPhone 16e) on the most recent available iOS version. To see the full list of available simulators and select from that list, provide `-d`/`--device` with no value.
The device to target. Can be either a UDID, a device name (e.g., `"iPhone 11"`), a device name and OS version (`"iPhone 11::iOS 13.3"`), or `auto`. `auto` is the default behavior; Briefcase will automatically select an "entry level" iPhone simulator (e.g., an iPhone SE, or iPhone 16e) on the most recent available iOS version. To see the full list of available simulators and connected physical devices, and select from that list, provide `-d`/`--device` with no value.

If any physical devices are known to your Mac, the list of iOS versions will include a *Physical devices* option. Devices that aren't ready to run apps (because they aren't paired with your Mac, don't have Developer Mode enabled, or can't be reached) are labeled with the reason. A physical device can also be selected using its name, or its UDID (as reported by `xcrun devicectl list devices --columns udid`). See [Deployment to physical iOS devices][ios-deploy] for details.

#### `-i <identity>` / `--identity <identity>`

The development signing identity to use when running on a physical device. Can be either the 40-digit hex checksum of the identity, or its full name (e.g., `"Apple Development: jane@example.com (A1B2C3D4E5)"`). If this option isn't provided when a physical device is selected, Briefcase will ask you to select from the development signing identities that are available. This option is ignored when running on a simulator.

## Application configuration

Expand Down Expand Up @@ -201,16 +217,32 @@ cleanup_paths = [

This will find and purge all `.a` content in your app's dependencies. You can add additional patterns to remove other problematic content.

### Deployment to Simulated and Physical iOS Devices { #ios-deploy }
### Deployment to physical iOS devices { #ios-deploy }

Briefcase can run your app on a physical iPhone or iPad running iOS or iPadOS 17 or later. Before you can deploy to a device, you need a development signing certificate, your Apple ID added to Xcode, and a device that is paired with your Mac and has Developer Mode enabled. A free Apple ID is sufficient. See [iOS code signing][code-signing-ios] for setup instructions.

When a device is connected, it will be offered as a target under *Physical devices* when you provide `-d`/`--device` with no value:

```console
$ briefcase run iOS -d
```

Briefcase will then ask you to select a development signing identity, unless you provide one with `-i`/`--identity`. Briefcase will build the app for the device, install it, and start it, streaming the app's output to the console until the app exits. Type CTRL-C to stop the app.

Running `briefcase run iOS` without `-d` will always select a simulator, even when a physical device is connected.

If the app has already been built for a physical device, Briefcase won't rebuild it. To rebuild the app (for example, to sign it with a different identity, or to renew an expired provisioning profile), run `briefcase build iOS -d`.

If you deploy to a physical device in debug mode, the debugger runs on the device, so it must be reachable over the network from your Mac. Use `--debugger-host 0.0.0.0` so that the debugger listens on all of the device's network interfaces, and connect your debugger to the device's IP address. Your Mac and device must be on the same network.

#### Troubleshooting

Briefcase provides support for deployment to simulated iOS devices through the command line.
* *The device isn't listed, or is labeled as not ready*: Confirm that the device is unlocked, paired with your Mac, and has Developer Mode enabled. If you select a device that isn't ready, Briefcase will describe how to fix the problem. You can check the state of your devices with `xcrun devicectl list devices`.
* *No development signing identities are available*: You need to create an Apple Development certificate. See [iOS code signing][code-signing-ios].
* *The app can't be launched, because the profile "has not been explicitly trusted by the user"*: On the device, open *Settings > General > VPN & Device Management*, select your Apple ID under *Developer App*, and tap *Trust*.
* *The bundle identifier can't be registered*: Bundle identifiers must be unique across all Apple developer teams. Change the [`bundle`][] of your app to one based on a domain that you control.
* *The app stops starting after a week*: Provisioning profiles for free Apple IDs expire after 7 days. Rebuild the app with `briefcase build iOS -d` to renew the profile.

If you want to deploy to a physical iOS device, you will need need to use Xcode through the following steps:
### Distributing iOS apps { #ios-distribute }

1. Run `briefcase open ios` in the command line. This will open your application in Xcode.
2. Setup your Apple Developer account with your certificate in Xcode.
3. In the project navigator, select your application at the top level (the root of the project).
4. Select the *Signing and Capabilities* tab in the editor area.
5. Select your Apple Developer team or individual account from the *Team* drop-down.
6. Select your specific device.
7. Press the run button.
Briefcase can't produce a distributable iOS artefact. To distribute your app through the App Store or TestFlight, run `briefcase open iOS` to open your project in Xcode, and use Xcode's app distribution workflow.
5 changes: 5 additions & 0 deletions docs/spelling_wordlist
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ IDEs
indygreg's
installable
iOS
iPadOS
jarsigner
JDK
jks
Expand Down Expand Up @@ -138,6 +139,7 @@ OpenSSL
openSUSE
OpenSuSE
OSX
passcode
passthrough
Passthrough
pbb
Expand Down Expand Up @@ -216,6 +218,7 @@ subprocess
subprocesses
TCP
templated
TestFlight
Tk
Tkinter
toml
Expand Down Expand Up @@ -252,6 +255,7 @@ verbing
visionOS
VM
VOC
VPN
watchOS
Wayland
WearOS
Expand All @@ -261,5 +265,6 @@ WPF
Wunjo
Xauth
Xcode
Xcode's
Xr
Xs
12 changes: 12 additions & 0 deletions src/briefcase/commands/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,16 @@ def _prepare_app_kwargs(

return args

def prepare_target(self, app: FinalizedAppConfig, **options):
"""Prepare the target that the app will run on.

This is invoked before determining whether the app needs to be built, so that
any selection that affects the build (such as the target device, which
determines the binary that is required) can be made.

:param app: The application to start
"""

@abstractmethod
def run_app(
self,
Expand Down Expand Up @@ -396,6 +406,8 @@ def __call__(
)
app = finalized[app.app_name]

self.prepare_target(app, **options)

template_file = self.bundle_path(app)
exec_file = self.binary_executable_path(app)
if (
Expand Down
138 changes: 138 additions & 0 deletions src/briefcase/integrations/xcode.py
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,89 @@ def get_device_state(tools: ToolCache, udid: str) -> str:
raise BriefcaseCommandError("Unable to run xcrun simctl.") from e


# The reasons a physical device can't be used for deployment.
DEVICE_NOT_PAIRED = "not paired"
DEVICE_DEVELOPER_MODE_DISABLED = "Developer Mode not enabled"
DEVICE_UNREACHABLE = "not reachable"


def get_physical_devices(
tools: ToolCache,
os_name: str,
) -> dict[str, dict[str, str | None]]:
"""Obtain the physical devices known to this machine.

The return value is a dictionary of devices, keyed by hardware UDID. Each device is
described by a dictionary containing its `name`, its `os_version`, and the reason
it can't be used for deployment (`not_ready`). `not_ready` is `None` if the device
can be used; otherwise, it is one of `DEVICE_NOT_PAIRED`,
`DEVICE_DEVELOPER_MODE_DISABLED` or `DEVICE_UNREACHABLE`.

:param tools: ToolCache of available tools
:param os_name: The OS of the devices to find. One of `"iOS"`, `"watchOS"`, or
`"tvOS"`.
:returns: A dictionary of physical devices.
"""
try:
devicectl_data = tools.subprocess.parse_output(
json_parser,
["xcrun", "devicectl", "list", "devices", "--json-output", "-", "-q"],
)
except CommandOutputParseError as e:
raise BriefcaseCommandError("Unable to parse output of xcrun devicectl") from e
except subprocess.CalledProcessError as e:
raise BriefcaseCommandError("Unable to run xcrun devicectl.") from e

devices = {}
for device in devicectl_data["result"]["devices"]:
# Xcode 27 deprecates the `hardwareProperties`, `deviceProperties` and
# `connectionProperties` dictionaries, replacing them with a `properties`
# dictionary. Use the deprecated dictionaries if they are present.
if "hardwareProperties" in device:
hardware = device["hardwareProperties"]
connection = device["connectionProperties"]
details = device["deviceProperties"]
name = details.get("name")
os_version = details.get("osVersionNumber")
paired = connection.get("pairingState") == "paired"
developer_mode = details.get("developerModeStatus") == "enabled"
reachable = connection.get("tunnelState") != "unavailable"
else:
properties = device["properties"]
hardware = properties["hardware"]
connection = properties["connection"]
software = properties.get("software", {})
name = properties.get("state", {}).get("name")
os_version = software.get("osVersionNumber", {}).get("stringValue")
paired = connection.get("pairingState") == "paired"
developer_mode = (
software.get("developerModeStatus", {}).get("enabled", {}).get("mode")
== 1
)
reachable = connection.get("state") != "unavailable"

# Simulated devices, and devices for other platforms, aren't candidates.
if hardware.get("reality") == "simulated" or hardware["platform"] != os_name:
continue

if not paired:
not_ready = DEVICE_NOT_PAIRED
elif not developer_mode:
not_ready = DEVICE_DEVELOPER_MODE_DISABLED
elif not reachable:
not_ready = DEVICE_UNREACHABLE
else:
not_ready = None

devices[hardware["udid"]] = {
"name": name,
"os_version": os_version,
"not_ready": not_ready,
}

return devices


# A regex pattern that matches the content returned by `security find-identity`
IDENTITY_RE = re.compile(r"\s*\d+\) ([0-9A-F]{40}) \"(.*)\"")

Expand All @@ -492,3 +575,58 @@ def get_identities(tools: ToolCache, policy: str | None = None) -> dict[str, str

except subprocess.CalledProcessError as e:
raise BriefcaseCommandError("Unable to run security find-identity.") from e


# A regex pattern that matches the SHA-1 hash and PEM-encoded certificate of each
# certificate returned by `security find-certificate -Z -p`
CERTIFICATE_RE = re.compile(
r"^SHA-1 hash: ([0-9A-F]{40})\n"
r"(-----BEGIN CERTIFICATE-----\n.*?-----END CERTIFICATE-----\n)",
re.MULTILINE | re.DOTALL,
)


def get_team_id(tools: ToolCache, identity_id: str, identity_name: str) -> str:
"""Obtain the development team ID for a signing identity.

The team ID is the organizational unit of the identity's certificate. The suffix in
the name of an Apple Development certificate can't be used, as it identifies the
team member, not the team.

:param tools: ToolCache of available tools
:param identity_id: The 40-digit hex checksum of the identity
:param identity_name: The name of the identity
:returns: The team ID for the identity.
"""
try:
output = tools.subprocess.check_output(
[
"security",
"find-certificate",
"-a",
"-c",
identity_name,
"-Z",
"-p",
],
)

# The output contains the hashes of each certificate matching the name,
# followed by the PEM-encoded certificate.
certificates = dict(CERTIFICATE_RE.findall(output))

if identity_id in certificates:
subject = tools.subprocess.check_output(
["openssl", "x509", "-noout", "-subject", "-nameopt", "RFC2253"],
input=certificates[identity_id],
)
if match := re.search(r"\bOU=([^,]+)", subject):
return match[1]
except subprocess.CalledProcessError as e:
raise BriefcaseCommandError(
f"Unable to inspect the certificate for signing identity {identity_name!r}."
) from e

raise BriefcaseCommandError(
f"Unable to determine the team ID for signing identity {identity_name!r}."
)
Loading
Loading