Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / iOS

Controlling iOS Devices Via C# Code on Windows OS

4.33/5 (4 votes)
19 Oct 2015CPOL8 min read 26.2K  
How to set up and manipulate an iOS device from a Windows C# App

Introduction

This article shows you how to manipulate an iOS device from C# code from a Windows environment.

Background

In order to use an iOS device, you must first install the Quamotion tools (built upon the libimobile codebase). This is open source. Download the tools from here:

Download the installer.

Pay particular attention to the list of supported iOS versions and devices.

Note that if you plan on installing and running an actual .ipa (a packaged app created on the Mac), then when you are building the application from XCode on the Mac, you must have a p12 (encryption file to sign your app), and a .mobileprovisioning file (that contains your devices DUID). You must also, in the project properties, set the correct identifier, i.e., com.my.app.

Build your app and make sure you can run it on the device from the XCode IDE first.

You can still use the other functions listed here without an actual .ipa.

When the .ipa has been installed on the device, it becomes a .app (application) file.

Preparing Your Windows PC

After you have installed the Quamotion tools, you will need to add the tool location to your system path. Click on Start -> Settings -> About -> System Info ->Advanced System Settings -> Environment Variables. In system variables, click on PATH, and Edit. Add your folder location to the path by pasting into the box, the path, separate it from the other folders with a semi-colon. My tools were here :

C:\Program Files (x86)\Quamotion\iMobileDevice

Now start up a command shell (cmd from the Start->Run), and make sure you can see the path, type in :

path

You should see the path to the Quamotion tools. Now try and list all USB connected devices :

idevice_id -l

You should see the DUIDs (Devices Unique Identifiers). If not, either your device is not supported, or it is not in a fit state, see below.

Preparing Your iOS Device

When using the tools, it is common to use the -u (lower case u, in MOST cases), in order to specify which device you want to talk to. If you have only one device, you can ignore this optional parameter. If you have multiple connected devices then pass in the -u followed by the DUID.

To obtain the DUID go to itunes, select the device (top left), then keep clicking on serial number on the general tab until you see the DUID. Of course you can also find the DUID on the actual device.

If you have a problem with your device from your C# application, always try and see if it works from the command line, for command line usage see my other paper :

http://www.codeproject.com/Reference/1041507/Commands-for-Controlling-an-iOS-device-in-Windows

If you need to find out how a tool works, simply pass in the -h for help argument e.g.

ideviceinfo -h

Plug in the device via USB (wireless is not supported).

Before you can use an iOS device from a Windows PC, there are a few things to do. Note NOT necessarily in this order - maybe activate, then pair, then mount:

  1. Trust the device - The device needs to be paired, so use this command to trust it to the PC, make sure you unlock the device and accept the trust dialog that comes up. Note that when you reboot the device, you must repeat this action.

    idevicepair pair

  2. Make sure the device is trusted:

    idevicepair validate
     
  3. Mount the developer disk image, this is necessary if you want to run applications on the device. To do this, you need to get two files from the itunes installation on the Mac (or maybe on the Windows installation). They are the .dmg and .dmg.signature. Navigate to the following folder on the MAC:
    //Applications/Xcode.app
    Then expand package from the XCode icon in finder in the applications folder.

    /Contents/Developer/Platforms/IPhoneOS.platform/DeviceSupport/<Device IOS Version> - my iphone version was 8.4.1 so navigate to the folder 8.4. I checked my device iOS version by using the phone, goto Settings>General->Software Update (make sure you are connected to the internet, otherwise it wil not show you).

    Copy the 2 files in there - DeveloperDiskImage.dmg and DeveloperDiskImage.dmg.signature.

    Then with these in the local directory, mount the disk image.

    ideviceimagemounter -u <DUID> -t Developer DeveloperDiskImage.dmg DeveloperDiskImage.dmg.signature

     
  4. Make sure the device is activated, use this command (this example uses the -u option): ideviceactivation activate -u <DUID>
     
  5. Use the command line to verify the device is working and connected correctly (this will list all information about the iOS device).

    ideviceinfo -u <DUID>

Now you should be good to go, let's look at the code.

References into C# Project/Solution

The first thing to note is that there are no new references to plug into your C# app. That's because we will be calling external executables (tools), and as such, we just need to kick off a process and pass in some command line arguments.

Code Examples

Here is a utility function for running a tool:

C#
public static String LaunchExternalExecutable(String executablePath, String arguments)
{
            if (String.IsNullOrWhiteSpace(executablePath) == true)
            {
                String errorMessage = String.Format(" Path is not valid. LaunchExternalExecutable called with invalid argument executablePath was empty.");
                Logger.Instance.WriteError(errorMessage);
                throw new ArgumentNullException(errorMessage);
            }

            String processOutput = "";

            ProcessStartInfo startInfo = new ProcessStartInfo()
            {
                CreateNoWindow = false,
                UseShellExecute = false,
                FileName = executablePath,
                WindowStyle = ProcessWindowStyle.Hidden,
                Arguments = arguments,
                RedirectStandardOutput = true
            };

            try
            {
               using (Process exeProcess = Process.Start(startInfo))
               {
                   processOutput = exeProcess.StandardOutput.ReadToEnd();
               }
            }
            catch (SystemException exception)
            {
                String errorMessage = String.Format("LaunchExternalExecutable - Device Failed to launch a tool with executable path {0}. {1}", executablePath, exception.ToString());
                Logger.Instance.WriteError(errorMessage);
                throw new Exception(errorMessage);
            }

            //Strip off extra characters - spaces, carriage returns, end of line etc
            processOutput = processOutput.Trim();
            processOutput = processOutput.TrimEnd(System.Environment.NewLine.ToCharArray());

            //Without this next change any text that contains
            //{X} will crash the String.Format inside the logger
            processOutput = processOutput.Replace('{', '[');
            processOutput = processOutput.Replace('}', ']');

            Logger.Instance.WriteInfo("LaunchExternalExecutable called. Output from tool : " + processOutput, "");
            return processOutput;
}

This C# code works for any tool/external executable, and allows the passing in of any number of arguments.

Note that it might not compile "as is", it just gives you a guide to what to do yourself. I check to make sure that I strip out any xml characters that can crash the log4net code before logging, take that out if your logging mechanism doesn't need that.

Here are all the tool names you will need along with the relevant command line arguments. So, pass in the tool name as the first argument to the function above, then fill in the command line arguments and pass them in as the second argument to the function.

Run An Installed .app (Application)

This will execute a pre-installed application on the device, you can pass in extra parameters to the actual .app file when it runs. Eg you might want to run MyTestProg -x ATestArg -y AnotherTestArg - this is supported.

Executable Tool (1st Argument):

idevicedebug

Arguments (2nd Argument)

//Argument 0 - IOS Device ID

//Argument 1 - Bundle id ie com.marcus.MyTestApp

//Argument 2 - All the extra params to pass to the application

-u {0} run {1} {2}

Example C#

LaunchCommandLineApp("idevicedebug", "-u 1234567890-1234567890 run com.marcus.MyTestApp -x XtraParmsForApp");

Reboot

Reboot the device, note this is not a good idea unless you really have to. It means you must re-pair the device afterwards, and that requires manual intervention via the trust dialog box that pops up on the device.

Executable Tool (1st Argument):

idevicedebug

Arguments (2nd Argument)

//Restart the device - NOT StartUP !

//Argument 0 - IOS Device ID

-u {0} restart

Example C#

LaunchCommandLineApp("idevicedebug", "-u 1234567890-1234567890 restart");

Get Device Information

This gets all the information about the connected device, for example, the version of OS on the device. There are many keys you can use to retriece what you need, the best thing to do is run this from the command line and pipe it into a txt file and then find the key you need :

ideviceinfo -u <DUID> -x > dave.txt

Here is how to use the get info with keys :

Executable Tool (1st Argument):

ideviceinfo

Arguments (2nd Argument)

//Get all the info about the device as XML

//Argument 0 - IOS Device ID

//Argument 1 - Information Key

-u {0} -k {1}

Keys (here are 4 examples - there are lots more !):

  • ProductVersion - OS Version
  • ActivationState - Activate State
  • CPUArchitecture - CPU Type
  • EthernetAddress - Mac Address

Example C#:

LaunchCommandLineApp("ideviceinfo", "-u 1234567890-1234567890 -k ProductVersion");

Pair the Device

This causes the trust dialog to pop up on the device, you must manually accept this in order to have comms between the Windows PC and the device.

Executable Tool (1st Argument):

idevicepair

Arguments (2nd Argument)

//Pair the device with this host

//Argument 0 - IOS Device ID

pair -u {0}

Example C#

LaunchCommandLineApp("idevicepair", "-u 1234567890-1234567890 pair");

Note use the following:

  • pair to pair
  • unpair to un-pair
  • validate to validate

Is the Application Installed on the Device/List All Applications Installed on Device?

You can test to see if the application is installed on the device. This actually lists all the applications installed on the device, so get the return from the tool, and do a String.Contains call on it with the app name.

Executable Tool (1st Argument):

 ideviceinstaller

Arguments (2nd Argument)

//List all applications installed on the device

//Argument 0 = IOS Device to ls

-u {0} -l -o xml

Example C#

LaunchCommandLineApp("ideviceinstaller", "-u 1234567890-1234567890 -l -o xml");

Install/Unistall an Application

This will install the specified application (.ipa file), on to the device. Note the .ipa will be verified to make sure it is a valid .ipa, and it has been signed, the identity matches and the provising DUID matches.

Executable Tool (1st Argument):

 ideviceinstaller

Arguments (2nd Argument)

//Installing an Application

//Argument 0 = Device Unique Identifier

//Argument 1 = Path to the Application name (.ipa file)

-u {0} -i {1}

Example:

LaunchCommandLineApp("ideviceinstaller", "-u 1234567890-1234567890 -i MyNumberOneAppInIstore.ipa"); 

 Note for un-installing use -u <DUID> -U <app name>, and note that the app name is the .app file, not the .ipa file name.

Conclusion

There are enough examples here showing how to talk to, and manipulate an iOS device from Windows. So that's it! Good luck with your iOS device programming from a Windows PC !

Many thanks to the guys at Quamotion - especially Frederik Carlier.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)