Click here to Skip to main content
13,260,089 members (48,472 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

9.3K views
11 bookmarked
Posted 19 Oct 2015

Controlling iOS Devices Via C# Code on Windows OS

, 19 Oct 2015
Rate this:
Please Sign up or sign in to vote.
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:

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)

Share

About the Author

marcus obrien
Technical Lead
Canada Canada
I have a blog here

http://www.electricalengineeringschools.org/blog/

And my robotics web site is here :

http://www.roboticsfordreamers.com/

I have been a software engineer for over 20 years now. I'm an expert in writing scalable restful web API services, which I've been doing for over 7 years now for games companies such as EA and Ubisoft. I've also worked on several video games, including Skate 2 and 3, NHL, Need for Speed, various Assassins Creed games, Far Cry 3 and 4, Driver San Francisco and most recently with a team of 15 on EA's UFC free to play. On this latest project I designed, implemented, tested (including load tests in Gatling and JUnit on AWS), deployed and supported all the web services for the game client, supporting up to a half a million active sessions.

I am proficient at programming in C, C++, C#, Java etc. I've developed many types of games, applications, SDKs and web services in Linux, Unix, iOS, Android and Windows.

My spare time is spent teaching and lecturing computing languages and science. I have a PhD in Artificial Intelligence (specialising in knowledge representation - Semantic networks with inference engines).

Currently I am also building an A.I. general purpose robot. The brains behind it are a mix of 6 Raspberry Pi and Banana Pros, with 2 USB cameras, SATA drive, Router Switch with inter-pi Comms, 2 motorised track systems, plus various sensors including motion/pir/sound etc.

The six pi's are split according to functions, including eyes (image processing/recognition), ears (speech processing and simulated speech),motor (object avoidance, environment mapping, drives all movement), entertainment (web browsing, media playing etc), brain (knowledge system, and adaptive learning/memory systems) and development system ( logging, diagnostics, debugging).

I am available as a consultant, so if you need to get something out the door quick, or want to set down an expandable and resilient framework, ping me !

You may also be interested in...

Pro
Pro

Comments and Discussions

 
Questionthought Pin
Nelek21-Oct-15 23:21
protectorNelek21-Oct-15 23:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171114.1 | Last Updated 19 Oct 2015
Article Copyright 2015 by marcus obrien
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid