Alert.png

Notice: This page contains information for the legacy Phidget21 Library.

Phidget21 is out of support. Bugfixes may be considered on a case by case basis.

Phidget21 does not support VINT Phidgets, or new USB Phidgets released after 2020. We maintain a selection of legacy devices for sale that are supported in Phidget21.

We recommend that new projects be developed against the Phidget22 Library.


Click on the 2phidget22.jpg button in the menu bar to go to the Phidget22 version of this page.

Alert.png

Language - iOS: Difference between revisions

From Phidgets Legacy Support
No edit summary
No edit summary
 
(71 intermediate revisions by 5 users not shown)
Line 1: Line 1:
Preamble about the language and its general strengths and weaknesses.
[[Category:Language]]
{{OSLang|[[File:icon-iOS.png|64x64px|alt=|link=]]|applications are built using the Cocoa Touch framework and the Objective C programming language, both developed by [http://www.apple.com Apple].}}
__TOC__


==Support==
==Introduction==
iOS has a complete API for all Phidgets devices, and code samples for PhidgetInterfaceKit devices.


For a complete list of our supported languages and their support status, [[Levels of Support|click here]].
{{LanguageSupport|iOS|nearly the complete Phidget API, including events. As iOS devices do not have USB ports, Phidgets can only be remotely controlled over a network, by using the [[Phidget WebService]]|the Phidget InterfaceKit, Hello World examples and a Skeleton starter project.|Xcode on OS X|}}


* Our honest opinion on how well this language is suited to controlling Phidgets. If it is a poor choice, suggest and link similar (better) languages.
==Quick Downloads==
* In this section, list any restrictions or limitations that this particular language may impose. For example, incompatibility with certain operating systems.
{{QuickDownloads|iOS|
* [{{SERVER}}/documentation/Phidget21_C_Doc.zip C API]|
{{ExampleQuickDownloads|{{SERVER}}/downloads/phidget21/libraries/ios/Phidget-iPhone.zip|(same file as iOS libraries)}}|
{{ExtraLibraryQuickDownloads|{{SERVER}}/downloads/phidget21/libraries/ios/Phidget-iPhone.zip|iOS|(same file as iOS examples)}}
{{MacQuickDownloads}}
}}
 
==Getting Started with Cocoa Touch==
 
If you are new to writing code for Phidgets, we recommend starting by running, then modifying existing examples. This will allow you to:
* Make sure your libraries are properly linked
* Go from source code to a test application as quickly as possible
 
As iOS development is primarily done on Xcode, we provide instructions for Xcode, specifically version 4.0.
 
====Use Our Examples====
 
Start by ensuring that the WebService is running on the computer that the Phidget is physically plugged in and connected to. This computer needs to have an USB port and can be an OS X system or any other [[Software Overview#Operating System Support|operating systems]] we support. For directions on how to set up and run the WebService, refer to the page [[Software Overview#Operating System Support|for that operating system]]
 
Then on the the OS X system that will be used for developing iOS applications, download and unpack the [{{SERVER}}/downloads/phidget21/libraries/ios/Phidget-iPhone.zip Phidget Examples for iOS]. The easiest way to confirm that your environment is set up properly will be to compile and run the HelloWorld iOS example.
Start by opening the HelloWorld.xcodeproj in Xcode.
 
Next, select your target destination that you want the application be ran on: an iOS device or simulator. For the purpose of this section, we will be using the simulator.
 
[[Image:IOS Xcode Destination.png||alt=|link=]]


==Development Environments and Compilers==
To run the example, click on the {{Code|Run}} button.


Describe each major compiler and notable differences or important information. (eg. framework versions) If there are known issues/workarounds mention them and link to the corresponding issue at the bottom of the page.
[[Image:IOS Xcode Run.png||alt=|link=]]


==Quick Downloads==
This program will detect for Phidgets that are attached/detached on the host computer. Go ahead, and attach or detach your devices! Here is an example output:
Before you can run your program, you need to set up the proper environment and get the necessary files off the Phidgets website.
Visit the drivers section at www.phidgets.com and get the latest:
* [http://www.phidgets.com/drivers.php Phidget Framework]
* [http://www.phidgets.com/drivers.php iOS Library]
You will need the Phidget Framework to use and to program with Phidgets. We also recommend that you download the following reference materials:
* [http://www.phidgets.com/documentation/Phidget21_C_Doc.zip API Manual]
* [http://www.phidgets.com/documentation/web/cdoc/index.html API Reference]
* [http://www.phidgets.com/downloads/examples/iOS_2.1.8.20110712.zip iOS Sample Code]
* You can find a high level discussion about programming with Phidgets in general on the [[General API]] page.  
* The [[Device Functionality]] page explains the general operational information for your device.


You may want to have these pages open while working through these instructions.
[[Image:IOS Webservice Example HelloWorld Output.png||alt=|link=]]


==Getting Started==
After confirming that the {{Code|HelloWorld}} example is working, you can proceed to run the example for your specific device. {{FindYourDevice}} Currently, the only device we provide example code for is the PhidgetInterfaceKit.


You will need the Phidget21 library and the iOS library to use and program with Phidgets.
Once you have the iOS examples running, we have a [[#Follow the Examples|teaching]] section below to help you follow them.
As iOS devices do not have USB ports, support for Phidgets is made available through the WebService.
The system that is hosting the Phidgets will need to have the Phidget21 library installed.
After the framework is installed, the WebService must be started.
For more information on the WebService, please see the [[Phidgets Webservice|Webservice Page]].


===Setting up a Phidgets Project===
====Write Your Own Code====


The Phidget examples were written in Objective-C and Xcode 4.0, and this tutorial assumes their use.
When you are building a project from scratch, or adding Phidget function calls to an existing project, you'll need to configure your development environment to properly link the Phidget iOS library. To begin:  
Other versions of Xcode should work as well and would be set up in a similar manner. In Xcode:
* Generate a new iOS Windows-based Application project with a descriptive name such as PhidgetTest.
* Set up the Provisioning Profiles and Code Signing settings, if necessary.
* Download the Phidget21 iOS library, extract the file, and move the iphoneos and the iphonesimulator folders, as well as the phidget21.h into the same directory as the the .xcodeproj file.
* In xCode, open up the Project Settings > Build Settings.
* In Linking > Other Linker Flags, follow these steps for both Debug, and Release:
** Select "Any iOS Simulator SDK" and enter:


<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
1. Generate a new iOS Windows-based application project with a descriptive name such as PhidgetTest.
<font size="3">
<source lang=c>


$(SRCROOT)/iphonesimulator/libPhidget21.a
[[File:IOS NewProject 1.png|link=|alt=New Project]]


</source>
[[File:IOS NewProject 2.png|link=|alt=New Project]]
</font>
</div>


:* Select "Any iOS SDK" and enter:
A {{Code|.xcodeproj}} project file will be created.


<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
2. Set up the Provisioning Profiles and Code Signing settings, if necessary.
<font size="3">
<source lang=c>


$(SRCROOT)/iphoneos/libPhidget21.a
3. Download the [{{SERVER}}/downloads/phidget21/libraries/ios/Phidget-iPhone.zip Phidget iOS library] and extract it.


</source>
4. Inside, you will find the {{Code|iphoneos}} and the {{Code|iphonesimulator}} folders. Move the two folders as well as the {{Code|phidget21.h}} into the same directory as the newly created {{Code|.xcodeproj}} file.
</font>
</div>


* In Search Path > Header Search Path, enter:
5. In Xcode, open up the Project Settings &rarr; Build Settings.


<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
6. In Linking &rarr; Other Linker Flags, follow these steps for both the Debug, and Release sections:  
<font size="3">
<source lang=c>


$(SRCROOT)
Select {{Code|Any iOS Simulator SDK}} and enter: {{Code|$(SRCROOT)/iphonesimulator/libPhidget21.a}}.


</source>
Select {{Code|Any iOS SDK}} and enter: {{Code|$(SRCROOT)/iphoneos/libPhidget21.a}}.
</font>
</div>


* In the header file, add a reference to phidget21.h:
[[File:IOS Add Library.png|link=|alt=Add Library]]


<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
7. In Search Paths &rarr; Header Search Paths, enter: {{Code|$(SRCROOT)}}.
<font size="3">
<source lang=objc>


#import "phidget21.h"
[[File:IOS Add Header.png|link=|alt=Add Header]]


</source>
8. In the header file, add a reference to {{Code|phidget21.h}}:
</font>
<div class="source">
<syntaxhighlight lang=objc>
  #import "phidget21.h"
</syntaxhighlight>
</div>
</div>


* A text field will be used for the purpose of capturing output. Open MainMenu.nib to bring up the Interface Builder. Drag a text field from the Library to the Window. 
The project now has access to Phidgets and we are ready to begin coding.
* Add a text field outlet in the header file. For example,
 
<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
<font size="3">
<source lang=objc>


    @interface PhidgetTestAppDelegate : NSObject <UIApplicationDelegate>{
Please note that the Phidget iPhone library also contains a sample skeleton xCode project for iOS. This project already contains project settings similar to those discussed above and it lets you quickly start on Phidgets development.
        IBOutlet UITextField *sensorValueTxt;
    }
    @property (nonatomic, retain) IBOutlet UIWindow *window;
    @property (nonatomic, retain) IBOutlet UITextField *sensorValueTxt;
    @end


</source>
The same [[#Follow the Examples|teaching]] section which describes the examples also has further resources for programming your Phidget.
</font>
 
</div>
==Follow the Examples==
 
By following the instructions above, you probably now have a working example and want to understand it better so you can change it to do what you want. This section has resources for you to learn from the examples and write your own.


* In the implementation file, add the following line to the implementation section:
Your main reference for writing iOS applications will be our C API information, with syntax for all of our functions:
<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
<font size="3">
<source lang=objc>


  @synthesize sensorValueTxt;
{{UsingAPhidgetInCodeGeneral|both of which are available in iOS|[{{SERVER}}/documentation/Phidget21_C_Doc.zip C API]}}


</source>
===API Support===
</font>
</div>


* Also, be sure release the object in the dealloc method [sensorValueTxt release];
Most of the C API is supported in iOS, with the exception of the local open calls. This is because there are no USB ports on iOS devices, so only the remote open calls can be used.
* Connect the PhidgetTestAppDelegate class instance to sensorValueTxt.  


The project now has access to Phidgets and we are ready to begin coding.
The following open calls are unsupported:
Please note that the iPhone library also contains a sample skeleton xCode project for iOS.
<div class="source"><syntaxhighlight lang=objc>
This project contains the neccessary project settings for Phidgets development.
  int CPhidget_open(CPhidgetHandle phid, int serialNumber)
Alternatively, you can use it to start developing with Phidgets.
  int CPhidget_openLabel(CPhidgetHandle phid, const char * label)
</syntaxhighlight></div>
===Code Snippets===


===Coding For Your Phidget===
Specific calls in iOS will differ in syntax from those on the [[General Phidget Programming]] page, but the concepts stay the same. 


A Phidget object will need to be declared. For example, we can declare a PhidgetInterfaceKit in the .h header file with:
It may help to have the [[General Phidget Programming]] page and this section open at the same time, because they parallel each other and you can refer to the Cocoa Touch syntax, as described on this page. However, many additional concepts are covered on the General Phidget Programming page on a high level, such as using multiple Phidgets, handling errors, and different styles of programming.
<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
<font size="3">
<source lang=objc>


  CPhidgetInterfaceKitHandle ifkit
For example, if we were using a [{{SERVER}}/products.php?product_id=1018 Phidget Interface Kit] as our device, the general calls would look like this:


</source>
====Step One: Initialize and Open====
</font>
</div>
 
The object name for any type of Phidget is listed in the API manual.
Every type of Phidget also inherits functionality from the Phidget base class.


===Connecting to the Phidget===
For opening a remote Phidget over the network using the WebService:


Next, the Phidget object needs to be initialized and the program needs to try and connect to the Phidget over the WebService through a call to openRemoteIP() or openRemote().
<div class="source"><syntaxhighlight lang=objc>
These calls will tell the program to continuously try to connect to a Phidget, based on the parameters given, even trying to reconnect if it gets disconnected.
  CPhidgetInterfaceKitHandle device;
This means that simply calling open does not guarantee you can use the Phidget immediately.
 
We can handle this by using event driven programming and tracking the AttachEvents and DetachEvents, or by calling waitForAttachment.
   // Open first detected Interface Kit, remotely with IP address and port
WaitForAttachment will block indefinitely until a connection is made to the Phidget, or an optional timeout is exceeded.
  CPhidget_openRemoteIP((CPhidgetHandle)device, -1, "192.168.3.33", 5001, NULL);
For example, we can connect to a PhidgetInterfaceKit in the .m implementation file with:
</syntaxhighlight></div>
 
<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
<font size="3">
<source lang=objc>
   
    @implementation PhidgetTest
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        CPhidgetInterfaceKit_create(&ifkit);    
        CPhidget_openRemoteIP((CPhidgetHandle)ifkit, -1, "192.168.2.163", 5001, NULL);
    }
    @end


</source>
Since the WebService is used to connect to the Phidget, the one connection per device limit does not apply.
</font>
</div>


The openRemoteIP() and openRemote() calls can be used with parameters to try and get the first device it can find over the network, and open it based on a serial number.
The open calls will tell the program to continuously try to connect to a Phidget, based on the parameters given, even trying to reconnect if it gets disconnected.  
The API manual provides more information on openRemoteIP() and openRemote().
This means that simply calling open does not guarantee you can use the Phidget immediately. We can handle this by using event driven programming and tracking the attach events and detach events.
One important thing to remember is that when working with Phidgets, a local connection will reserve the device until closed.  
This prevents any other instances from retrieving data from the Phidget, including other programs.
The one connection per device limit does not apply when exclusively using the Phidget Webservice.
At the end of your program, don’t forget to call close to free any locks on the Phidget.


<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
====Step Two: Wait for Attachment (plugging in) of the Phidget====  
<font size="3">
<source lang=objc>


  - (void)applicationWillTerminate:(UIApplication *)application
To use the Phidget, it must be plugged in (attached).  We can handle this simply by calling {{Code|CPhidget_waitForAttachment}}. This function works for any Phidget. {{Code|CPhidget_waitForAttachment}} will block indefinitely until a connection is made to the Phidget, or an optional timeout is exceeded:
  {
      CPhidget_close((CPhidgetHandle)ifkit);
      CPhidget_delete((CPhidgetHandle)ifkit);
  }


</source>
<div class="source">
</font>
<syntaxhighlight lang=objc>
  int serialNum;
  CPhidget_waitForAttachment(10000);
  CPhidget_getSerialNumber((CPhidgetHandle)device, &serialNum);
  NSLog("%d attached!", serialNum);
</syntaxhighlight>
</div>
</div>


===Event Driven Programming===
Sometimes, it makes more sense to handle the attachment via an event.  This would be in instances where the Phidget is being plugged and unplugged, and you want to handle these incidents.  Or, when you want to use event-driven programming because you have a GUI-driven program.  In these cases, an event-driven code snippet to handle the attachment might look something like this.


We recommend the use of event driven programming when working with Phidgets.
First, you hook an event handler with the following code:
We can hook an event handler at loading with the following code:
<div class="source">
 
<syntaxhighlight lang=objc>
<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
  - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
<font size="3">
    ... 
<source lang=objc>
    CPhidgetManager_set_OnAttach_Handler(manager, gotAttach, self);
    ...
  }
</syntaxhighlight>
</div>


    CPhidgetInterfaceKit_set_OnSensorChange_Handler(ifkit, gotSensorChange, self);
Next, the callback method needs to be set up:
<div class="source">
<syntaxhighlight lang=objc>
  // ========== Event Handling Setup Functions ==========
  int gotAttach(CPhidgetHandle phid, void *context) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
      
      
</source>
    //invokes the DeviceAttach event method on the main thread and block the main thread until after the DeviceAttach method finishes
</font>
    //A bad access exception may occur if you set waitUntilDone to No
    [(id)context performSelectorOnMainThread:@selector(DeviceAttach:)
        withObject:[NSValue valueWithPointer:phid]
                                            waitUntilDone:YES];
    [pool release];
    return 0;
  }
</syntaxhighlight>
</div>
</div>


Next, the callback method needs to be set up before it can be used. For example,
Above, the {{Code|DeviceAttach}} method is invoked on the main thread. The {{Code|NSAutoreleasePool}} object is created to clean up released objects on the event thread, and is released at the end of the method. The {{Code|DeviceAttach}} method is defined as follows:
 
<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
<font size="3">
<source lang=objc>
 
    int gotSensorChange(CPhidgetInterfaceKitHandle phid, void *context, int ind, int val)
    {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        [(id)context performSelectorOnMainThread:@selector(SensorChange:)
        withObject:[NSArray arrayWithObjects:[NSNumber numberWithInt:ind], [NSNumberGetting_Started_iOS created: 06/16/11 Page 4
        numberWithInt:val], nil] waitUntilDone:NO];
        [pool release];
        return 0;
    }


</source>
<div class="source">
</font>
<syntaxhighlight lang=objc>
  // ========== Event Handling Functions ==========
  - (void)DeviceAttach:(NSValue *)phid
  {
    int phidgetSerial;
    const char * phidgetName;
   
    CPhidget_getSerialNumber((CPhidgetHandle)[phid pointerValue], &phidgetSerial);
    CPhidget_getDeviceName((CPhidgetHandle)[phid pointerValue], &phidgetName);
   
    outputField.text = [NSString stringWithFormat:@"%@Hello Device %@, Serial Number: %d\n\n", outputField.text, [NSString stringWithCString:phidgetName encoding:NSASCIIStringEncoding], phidgetSerial];
  }
</syntaxhighlight>
</div>
</div>


Above, the SensorChange method is invoked on the main thread. Event data is stored in a NSArray, which in turn is sent as a single argument to the SensorChange method.  
With this function, the code inside {{Code|DeviceAttach}} will get executed every time the PhidgetInterfaceKit is attaches to the computer. Some events such as Attach and Detach belong to the base Phidget object and thus are common to all types of Phidgets. Please refer to the API manual and the iOS examples for a list of events and their usage.
The NSAutoreleasePool object is created to clean up released objects on the event thread, and is released at the end of the method.  
The SensorChange method is defined as follows:


<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
====Step Three: Do Things with the Phidget====
<font size="3">
<source lang=objc>
    - (void)SensorChange:(NSArray *)sensorChangeData
    {
        int sensorIndex, sensorValue;
        sensorIndex = [[sensorChangeData objectAtIndex:0] intValue];
        sensorValue = [[sensorChangeData objectAtIndex:1] intValue];
        _sensorValueTxt.text = [NSString stringWithFormat:@"Sensor: %d, Value: %d",
        sensorIndex, sensorValue]];
    }


</source>
You can read data and interact with your Phidget both by polling it for its current state (or to set a state), or by catching events that trigger when the data changes.
</font>
 
</div>
For our [http://www.phidgets.com/products.php?product_id=1018 PhidgetInterfaceKit 8/8/8], the polling method of getting the current sensor state and setting an output state looks something like this:


With this function, the code inside SensorChange will get executed every time the PhidgetInterfaceKit reports a change on one of its analog inputs.
<div class="source">
Some events such as Attach and Detach belong to the base Phidget object and thus are common to all types of Phidgets. Please refer to the API manual and the iOS examples for a list of events and their usage.
<syntaxhighlight lang=objc>


===Working directly with the Phidget===
  # Get a data point from Analog Port 0
  int sensorValue;
  CPhidgetInterfaceKit_getSensorValue(device, 0, &sensorValue);
  [sensorValueTxt setintValue: sensorValue];


Some values can be read and sent directly to the Phidget, simply use the C API functions such as CPhidgetInterfaceKit_getSensorValue for PhidgetInterfaceKits.
  # Set digital output port 0 to be on
 
  CPhidgetInterfaceKit_setOutputState(device, 0, 1);  
<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
<font size="3">
<source lang=objc>


  int sensorIndex = 0;
</syntaxhighlight>
  int sensorValue;
  CPhidgetInterfaceKit_getSensorValue(ifkit, sensorIndex, &sensorValue);
  _sensorValueTxt.text = [NSString stringWithFormat:@"Sensor: %d, Value: %d",
  sensorIndex, sensorValue]];
</source>
</font>
</div>
</div>
   
These functions can be used inside a polling loop as an alternative to event driven programming.


===Working with multiple Phidgets===
====Step Four: Close and Delete====


Multiple Phidgets of the same type can easily be run inside the same program.
At the end of your program, don’t forget to call {{Code|CPhidget_close()}} and {{Code|CPhidget_delete()}} to free any locks on the Phidget that the {{Code|CPhidget_open()}} call put in place!
In our case, it  requires another InterfaceKit instance to be defined and initialized.
The new instance can then be set up, opened and used in the same process as the previous one.
If the application needs to distinguish between the devices, open can be called with the serial number of a specific Phidget.


===Other Phidgets===
<div class="source">
<syntaxhighlight lang=objc>
  CPhidget_close((CPhidgetHandle)ifkit);
  CPhidget_delete((CPhidgetHandle)ifkit);
</syntaxhighlight>
</div>


The design given in this document can also be followed for almost all Phidgets.
{{MoreHowTos}}
For example, if you were using a PhidgetRFID instead of an PhidgetInterfacekit, you would declare an RFID object instead of an InterfaceKit. The methods and events available would change but they can be accessed in a similar manner.


==Building your Project==
The ''complete'' set of functions you have available for all Phidgets can be found in the [{{SERVER}}/documentation/Phidget21_C_Doc.zip C API]. You can also find more description on any device-specific function in the Device API for your specific Phidget, which can be found in its [[:Category:UserGuide|user guide]].
Describe the different ways a project could be built using this language.


==Common Problems and Solutions/Workarounds==
==Common Problems and Solutions/Workarounds==
Here you can put various frequent problems and our recommended solutions.
 
None at this time.

Latest revision as of 19:19, 6 June 2017

applications are built using the Cocoa Touch framework and the Objective C programming language, both developed by Apple.

Introduction

If this is your first time working with a Phidget, we suggest starting with the Getting Started page for your specific device. This can be found in the user guide for your device. That page will walk you through installing drivers and libraries for your operating system, and will then bring you back here to use iOS specifically.

iOS is capable of using nearly the complete Phidget API, including events. As iOS devices do not have USB ports, Phidgets can only be remotely controlled over a network, by using the Phidget WebService. We also provide example code in iOS for the Phidget InterfaceKit, Hello World examples and a Skeleton starter project.

iOS can be developed with Xcode on OS X.

You can compare iOS with our other supported languages.

Quick Downloads

Just need the iOS documentation, drivers, libraries, and examples? Here they are:

Documentation

Example Code

Libraries and Drivers


Getting Started with Cocoa Touch

If you are new to writing code for Phidgets, we recommend starting by running, then modifying existing examples. This will allow you to:

  • Make sure your libraries are properly linked
  • Go from source code to a test application as quickly as possible

As iOS development is primarily done on Xcode, we provide instructions for Xcode, specifically version 4.0.

Use Our Examples

Start by ensuring that the WebService is running on the computer that the Phidget is physically plugged in and connected to. This computer needs to have an USB port and can be an OS X system or any other operating systems we support. For directions on how to set up and run the WebService, refer to the page for that operating system

Then on the the OS X system that will be used for developing iOS applications, download and unpack the Phidget Examples for iOS. The easiest way to confirm that your environment is set up properly will be to compile and run the HelloWorld iOS example. Start by opening the HelloWorld.xcodeproj in Xcode.

Next, select your target destination that you want the application be ran on: an iOS device or simulator. For the purpose of this section, we will be using the simulator.

To run the example, click on the Run button.

This program will detect for Phidgets that are attached/detached on the host computer. Go ahead, and attach or detach your devices! Here is an example output:

After confirming that the HelloWorld example is working, you can proceed to run the example for your specific device. The source file will be named the same as the software object for your device. If you are not sure what the software object for your device is, find your Phidget on our webpage, and then check the API documentation for it. Currently, the only device we provide example code for is the PhidgetInterfaceKit.

Once you have the iOS examples running, we have a teaching section below to help you follow them.

Write Your Own Code

When you are building a project from scratch, or adding Phidget function calls to an existing project, you'll need to configure your development environment to properly link the Phidget iOS library. To begin:

1. Generate a new iOS Windows-based application project with a descriptive name such as PhidgetTest.

New Project

New Project

A .xcodeproj project file will be created.

2. Set up the Provisioning Profiles and Code Signing settings, if necessary.

3. Download the Phidget iOS library and extract it.

4. Inside, you will find the iphoneos and the iphonesimulator folders. Move the two folders as well as the phidget21.h into the same directory as the newly created .xcodeproj file.

5. In Xcode, open up the Project Settings → Build Settings.

6. In Linking → Other Linker Flags, follow these steps for both the Debug, and Release sections:

Select Any iOS Simulator SDK and enter: $(SRCROOT)/iphonesimulator/libPhidget21.a.

Select Any iOS SDK and enter: $(SRCROOT)/iphoneos/libPhidget21.a.

Add Library

7. In Search Paths → Header Search Paths, enter: $(SRCROOT).

Add Header

8. In the header file, add a reference to phidget21.h:

  #import "phidget21.h"

The project now has access to Phidgets and we are ready to begin coding.

Please note that the Phidget iPhone library also contains a sample skeleton xCode project for iOS. This project already contains project settings similar to those discussed above and it lets you quickly start on Phidgets development.

The same teaching section which describes the examples also has further resources for programming your Phidget.

Follow the Examples

By following the instructions above, you probably now have a working example and want to understand it better so you can change it to do what you want. This section has resources for you to learn from the examples and write your own.

Your main reference for writing iOS applications will be our C API information, with syntax for all of our functions:

  • C API (This is the complete set of functions you have available for all Phidgets)
  • Device Specific APIs - The one for your Phidget can be found in its user guide.

To learn the details behind opening, configuring, using, and closing your Phidget, try the General Phidget Programming page. That page also describes using the Phidget in an event-driven manner and in a traditional manner, both of which are available in iOS.

API Support

Most of the C API is supported in iOS, with the exception of the local open calls. This is because there are no USB ports on iOS devices, so only the remote open calls can be used.

The following open calls are unsupported:

  int CPhidget_open(CPhidgetHandle phid, int serialNumber)
  int CPhidget_openLabel(CPhidgetHandle phid, const char * label)

Code Snippets

Specific calls in iOS will differ in syntax from those on the General Phidget Programming page, but the concepts stay the same.

It may help to have the General Phidget Programming page and this section open at the same time, because they parallel each other and you can refer to the Cocoa Touch syntax, as described on this page. However, many additional concepts are covered on the General Phidget Programming page on a high level, such as using multiple Phidgets, handling errors, and different styles of programming.

For example, if we were using a Phidget Interface Kit as our device, the general calls would look like this:

Step One: Initialize and Open

For opening a remote Phidget over the network using the WebService:

  CPhidgetInterfaceKitHandle device;
 
  // Open first detected Interface Kit, remotely with IP address and port
  CPhidget_openRemoteIP((CPhidgetHandle)device, -1, "192.168.3.33", 5001, NULL);

Since the WebService is used to connect to the Phidget, the one connection per device limit does not apply.

The open calls will tell the program to continuously try to connect to a Phidget, based on the parameters given, even trying to reconnect if it gets disconnected. This means that simply calling open does not guarantee you can use the Phidget immediately. We can handle this by using event driven programming and tracking the attach events and detach events.

Step Two: Wait for Attachment (plugging in) of the Phidget

To use the Phidget, it must be plugged in (attached). We can handle this simply by calling CPhidget_waitForAttachment. This function works for any Phidget. CPhidget_waitForAttachment will block indefinitely until a connection is made to the Phidget, or an optional timeout is exceeded:

  int serialNum;
  CPhidget_waitForAttachment(10000);
  CPhidget_getSerialNumber((CPhidgetHandle)device, &serialNum);
  NSLog("%d attached!", serialNum);

Sometimes, it makes more sense to handle the attachment via an event. This would be in instances where the Phidget is being plugged and unplugged, and you want to handle these incidents. Or, when you want to use event-driven programming because you have a GUI-driven program. In these cases, an event-driven code snippet to handle the attachment might look something like this.

First, you hook an event handler with the following code:

  - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    ...   
    CPhidgetManager_set_OnAttach_Handler(manager, gotAttach, self);
    ...
  }

Next, the callback method needs to be set up:

  // ========== Event Handling Setup Functions ==========
  int gotAttach(CPhidgetHandle phid, void *context) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    //invokes the DeviceAttach event method on the main thread and block the main thread until after the DeviceAttach method finishes
    //A bad access exception may occur if you set waitUntilDone to No
    [(id)context performSelectorOnMainThread:@selector(DeviceAttach:)
     					     withObject:[NSValue valueWithPointer:phid]
                                             waitUntilDone:YES];
    [pool release];
    return 0;
  }

Above, the DeviceAttach method is invoked on the main thread. The NSAutoreleasePool object is created to clean up released objects on the event thread, and is released at the end of the method. The DeviceAttach method is defined as follows:

  // ========== Event Handling Functions ==========
  - (void)DeviceAttach:(NSValue *)phid
  {
    int phidgetSerial;
    const char * phidgetName;
    
    CPhidget_getSerialNumber((CPhidgetHandle)[phid pointerValue], &phidgetSerial);
    CPhidget_getDeviceName((CPhidgetHandle)[phid pointerValue], &phidgetName);
    
    outputField.text = [NSString stringWithFormat:@"%@Hello Device %@, Serial Number: %d\n\n", outputField.text, [NSString stringWithCString:phidgetName encoding:NSASCIIStringEncoding], phidgetSerial];
  }

With this function, the code inside DeviceAttach will get executed every time the PhidgetInterfaceKit is attaches to the computer. Some events such as Attach and Detach belong to the base Phidget object and thus are common to all types of Phidgets. Please refer to the API manual and the iOS examples for a list of events and their usage.

Step Three: Do Things with the Phidget

You can read data and interact with your Phidget both by polling it for its current state (or to set a state), or by catching events that trigger when the data changes.

For our PhidgetInterfaceKit 8/8/8, the polling method of getting the current sensor state and setting an output state looks something like this:

  # Get a data point from Analog Port 0
  int sensorValue;
  CPhidgetInterfaceKit_getSensorValue(device, 0, &sensorValue);
  [sensorValueTxt setintValue: sensorValue];

  # Set digital output port 0 to be on
  CPhidgetInterfaceKit_setOutputState(device, 0, 1);

Step Four: Close and Delete

At the end of your program, don’t forget to call CPhidget_close() and CPhidget_delete() to free any locks on the Phidget that the CPhidget_open() call put in place!

  CPhidget_close((CPhidgetHandle)ifkit);
  CPhidget_delete((CPhidgetHandle)ifkit);

More How-To's

The General Phidget Programming page gives more information about:

The complete set of functions you have available for all Phidgets can be found in the C API. You can also find more description on any device-specific function in the Device API for your specific Phidget, which can be found in its user guide.

Common Problems and Solutions/Workarounds

None at this time.