<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>musicalgeometry &#187; code</title>
	<atom:link href="http://www.musicalgeometry.com/archives/category/code/feed" rel="self" type="application/rss+xml" />
	<link>http://www.musicalgeometry.com</link>
	<description>sound, code, &#38; DIY tech</description>
	<lastBuildDate>Sat, 24 Jul 2010 16:32:17 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Plug-And-Play OpenAL / AVFoundation Sound Engine For iPhone Apps</title>
		<link>http://www.musicalgeometry.com/archives/912</link>
		<comments>http://www.musicalgeometry.com/archives/912#comments</comments>
		<pubDate>Thu, 25 Feb 2010 21:17:47 +0000</pubDate>
		<dc:creator>Jason Job</dc:creator>
				<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[sound]]></category>

		<guid isPermaLink="false">http://www.musicalgeometry.com/?p=912</guid>
		<description><![CDATA[I recently found a great sound engine for iPhone applications that is pretty much plug-and-play. This sound engine was written by Alex Restrepo under a creative commons attribution-share alike licence, so you are free to use it so long as &#8230; <a href="http://www.musicalgeometry.com/archives/912">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I recently found a great sound engine for iPhone applications that is pretty much plug-and-play.</p>
<div id="attachment_913" class="wp-caption alignnone" style="width: 510px"><a href="http://www.musicalgeometry.com/wp-content/uploads/2010/02/openal.jpg"><img class="size-full wp-image-913 " style="border: 1px solid black;" title="openal" src="http://www.musicalgeometry.com/wp-content/uploads/2010/02/openal.jpg" alt="" width="500" height="268" /></a><p class="wp-caption-text">OpenAL lets you play multiple sounds at once</p></div>
<p>This sound engine was written by <a href="http://homepage.mac.com/alexrestrepo/indexmain.html">Alex Restrepo</a> under a creative commons attribution-share alike licence, so you are free to use it so long as you attribute the code to the author and if you change it and share it you must do so under the same license.  I have corrected one small mistake (a semi-colon where it should not have been) and also edited the formatting of the code to my personal preference. You can get an Xcode example project that uses the sound engine <a href="http://www.jasonjob.net/share/SoundEngineExample.zip">here</a>. If you just want the sound engine itself you can get it <a href="http://www.jasonjob.net/share/SoundEngine.zip">here</a>.  If you look at the <a href="http://www.jasonjob.net/share/SoundEngineExample.zip">example project</a> you will see how easy this sound engine is to use. It provides simple methods for playing and managing background music and for playing sound effects on top. These classes use AVFoundation to play the background music and OpenAL to play other sounds on top. I am not informed enough about either of these to know what advantages or disadvantages this may offer but will look into it and possibly do a pure OpenAL version.  To add the sound engine to your own project just add the class files included in <a href="http://www.jasonjob.net/share/SoundEngine.zip">SoundEngine.zip</a> to your project. Also be sure to add the OpenAL.framework, AVFoundation.framework and the AudioToolbox.framework otherwise you will get a host of strange errors.  You have the option of using the CMOpenALSoundManager as a singleton. If you do use it as a singleton (you can do this by setting USE_AS_SINGLETON to 1 at the top of CMOpenALSoundManager.h) you just need to initialize it somewhere in your code with:</p>
<pre><code>[[CMOpenALSoundManager sharedCMOpenALSoundManager] init];</code></pre>
<p>You also need to enumerate the tags for your sounds (ideally somewhere that every class that needs them will have access to them):</p>
<pre><code>enum mySoundIds {
BUTTONSOUND1
        BUTTONSOUND2
        SUCCESSSOUND
        ERRORSOUND
};</code></pre>
<p>You can then add your sound effects by passing an array of sound file names like so:</p>
<pre><code>[CMOpenALSoundManager sharedCMOpenALSoundManager].soundFileNames = mySoundFileNamesArray;</code></pre>
<p>To access your sound manager from anywhere in your project make sure you have included the CMOpenSoundManager header file and then reference the sound manager with:</p>
<pre><code>[CMOpenALSoundManager sharedCMOpenALSoundManager]</code></pre>
<p>Here is an example of playing some background music and then playing a sound effect:</p>
<pre><code>[[CMOpenALSoundManager sharedCMOpenALSoundManager] playBackgroundMusic:@"backgroundLoop.m4a"];
[[CMOpenALSoundManager sharedCMOpenALSoundManager] playSoundWithID:BUTTONSOUND1];</code></pre>
<p>One thing that I am not satisfied about with this system is the need for the enumeration. The reason being that you need to know which order the sounds are going to be loaded so that the correct sounds match the correct enum value. A better way in my opinion would be to use NSString keys, so that when you load a sound, you also pass a key. This is the approach taken in the code on the <a href="http://www.gehacktes.net/2009/03/iphone-programming-part-6-multiple-sounds-with-openal/">gethacktes.net</a> blog, which is another great resource for OpenAL on the iPhone. Doing it this way allows you to lazy load sounds in any order. If I make that change I will be sure to post it here.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.musicalgeometry.com/archives/912/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Xcode Script For Creating Properties From Instance Variables For UIViewController</title>
		<link>http://www.musicalgeometry.com/archives/904</link>
		<comments>http://www.musicalgeometry.com/archives/904#comments</comments>
		<pubDate>Wed, 24 Feb 2010 07:26:29 +0000</pubDate>
		<dc:creator>Jason Job</dc:creator>
				<category><![CDATA[OSX]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[XCode]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[hack]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[script]]></category>

		<guid isPermaLink="false">http://www.musicalgeometry.com/?p=904</guid>
		<description><![CDATA[One of my favourite blogs on the net is Matt Gallagher&#8217;s Cocoa with Love. Today I was investigating ways to speed up my workflow in Xcode and I found a great mixed Perl and AppleScript script already written by Matt a &#8230; <a href="http://www.musicalgeometry.com/archives/904">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>One of my favourite blogs on the net is Matt Gallagher&#8217;s <a href="http://cocoawithlove.com/">Cocoa with Love</a>. Today I was investigating ways to speed up my workflow in Xcode and I found a great mixed Perl and AppleScript script already written by Matt a couple of years ago.</p>
<div id="attachment_905" class="wp-caption alignnone" style="width: 637px"><a href="http://cocoawithlove.com/"><img class="size-full wp-image-905 " style="border: 1px solid black;" title="cocoawithlove" src="http://www.musicalgeometry.com/wp-content/uploads/2010/02/cocoawithlove.png" alt="" width="627" height="139" /></a><p class="wp-caption-text">A fantastic resource for Cocoa, Objective-C and programming in general</p></div>
<p>The script called <a href="http://projectswithlove.com/projects/PropertyFromInstanceVariable.zip">PropertyFromInstanceVariable</a> had already been added to by a couple of other people, Yung-Luen Lan &amp; <a href="http://github.com/mschrag/xcode_property_from_ivar">Mike Schrag</a> and <a href="http://www.bernard-web.com/pierre/blog/">Pierre Bernard</a> and I have now shaped it for my own specific needs, and possibly yours too.</p>
<p>The tedium I was trying to eliminate was the process of creating Objective-C properties from instance variables and doing basic memory management on them. This is a repetitive process that seems more appropriate to hand off to the machine.</p>
<p>Matt&#8217;s script allows you to take an instance variable defined in your interface file and automatically create a property for it, synthesize the property in the implementation, add a release statement and set the property to NULL in the dealloc method.</p>
<p>For example, running the script on this:</p>
<pre><code>NSString *myString;</code></pre>
<p>would automatically create this in the interface:</p>
<pre><code>@property (nonatomic, retain) NSString *myString;</code></pre>
<p>this at the top of the implementation:</p>
<pre><code>@synthesize myString;</code></pre>
<p>and adds these two lines to the dealloc method:</p>
<pre><code>[myString release];
myString = NULL;</code></pre>
<p>Because this script was written before the viewDidUnload method had been added to the UIViewController class it didn&#8217;t make use of the viewDidUnload method. I wanted to update it to set the retaining references to subviews in the view hierarchy to nil. These reference properties may have been set through IBOutlets when loading a nib or programmatically in the loadView method.</p>
<p>I have now modified the script to reflect my own coding habits. It still creates the property, synthesizes it and adds a release to the dealloc method, but if the class is a subclass of UIViewController then this is placed in viewDidUnload like so:</p>
<pre><code>self.myString = nil;</code></pre>
<p>This script can be run on multiple instance variables at once and greatly cuts down on the time it takes to set up a new class. Instructions on installing the script can be found <a href="http://cocoawithlove.com/2008/12/instance-variable-to-synthesized.html">here</a>.</p>
<p>You can get my fork of the script on <a href="http://github.com/jj0b/xcode_property_from_ivar">github</a>.</p>
<p>NOTE: I have updated to script and edited this post to reflect those changes. All links are to the most recent version.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.musicalgeometry.com/archives/904/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Online JSON Validator</title>
		<link>http://www.musicalgeometry.com/archives/887</link>
		<comments>http://www.musicalgeometry.com/archives/887#comments</comments>
		<pubDate>Wed, 03 Feb 2010 04:44:29 +0000</pubDate>
		<dc:creator>Jason Job</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[online]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://www.musicalgeometry.com/?p=887</guid>
		<description><![CDATA[I was creating some JSON data with PHP to pass to an iPhone app today and I found a great online JSON validation tool: JSONLint: The JSON Validator. Just plunk your JSON string into the window and press the validate button. &#8230; <a href="http://www.musicalgeometry.com/archives/887">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I was creating some JSON data with PHP to pass to an iPhone app today and I found a great online JSON validation tool: <a href="http://www.jsonlint.com/">JSONLint: The JSON Validator</a>.</p>
<div id="attachment_888" class="wp-caption alignnone" style="width: 218px"><a href="http://www.musicalgeometry.com/wp-content/uploads/2010/02/jsonvalidate.png"><img class="size-medium wp-image-888 " style="border: 1px solid black;" title="jsonvalidate" src="http://www.musicalgeometry.com/wp-content/uploads/2010/02/jsonvalidate-208x300.png" alt="" width="208" height="300" /></a><p class="wp-caption-text">The JSON Validator</p></div>
<p>Just plunk your JSON string into the window and press the validate button. Voila, not only are you told if your JSON string is valid but it also arranges your JSON data in an easily readable hierarchy. The JSON Validator was made and shared by the good folks at <a href="http://lab.arc90.com/">lab.ac9.com</a>.Thank you arc90!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.musicalgeometry.com/archives/887/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>When To Use self.myObject Instead Of myObject In iPhone Programming</title>
		<link>http://www.musicalgeometry.com/archives/872</link>
		<comments>http://www.musicalgeometry.com/archives/872#comments</comments>
		<pubDate>Mon, 25 Jan 2010 18:36:52 +0000</pubDate>
		<dc:creator>Jason Job</dc:creator>
				<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[iPhone]]></category>

		<guid isPermaLink="false">http://www.musicalgeometry.com/?p=872</guid>
		<description><![CDATA[I have seen a lot of confusion on the topic of when and why to reference an object using self.myObject versus just plain myObject. It took me a while to understand this myself, and please, if I am mistaken in &#8230; <a href="http://www.musicalgeometry.com/archives/872">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I have seen a lot of confusion on the topic of when and why to reference an object using self.myObject versus just plain myObject. It took me a while to understand this myself, and please, if I am mistaken in my explanation, set me right, but here it is as I understand it.</p>
<div id="attachment_878" class="wp-caption alignnone" style="width: 310px"><a href="http://www.musicalgeometry.com/wp-content/uploads/2010/01/objective_c.jpg"><img class="size-medium wp-image-878 " style="border: 1px solid black;" title="objective_c" src="http://www.musicalgeometry.com/wp-content/uploads/2010/01/objective_c-300x225.jpg" alt="" width="300" height="225" /></a><p class="wp-caption-text">Apparently some people don&#39;t like Objective-C</p></div>
<p>If you reference an object in your implementation that you declared in your header with @property and then used @synthesize in your implementation to automatically create getter and setter methods for the object, then using self.myObject  = newObject will call the setter and references to self.myObject will call the getter. As far as I know, if you are just referencing your object you don&#8217;t need to use the getter unless you are trying to distinguish from an object with the same name. When you assign your object however, the distinction becomes very important because everywhere you write:</p>
<pre><code>self.myObject = newObject;</code></pre>
<p>you are actually sending the message:</p>
<pre><code>[self setMyObject:newObject];</code></pre>
<p>which under the hood looks like:</p>
<pre><code>objc_msgSend(self, @selector(setMyObject:), newObject);</code></pre>
<p>The consequence of using self.myObject in this way is that myObject will use whatever retain property you set in the @property declaration. So if you set up myObject like so:</p>
<pre><code>@property (nonatomic, retain) MyObjectClass *myObject;</code></pre>
<p>then the value of myObject will be retained even after newObject has been deallocated.</p>
<p>If instead you had assigned myObject like this:</p>
<pre><code>myObject = newObject;</code></pre>
<p>then myObject is just the same as newObject. Therefore if newObject is deallocated then myObject will be pointing to a meaningless memory address. Probably not what you want.</p>
<p>So, here is an example:</p>
<pre><code>.h file
...
UIView *myUIView;
...
@property (nonatomic, retain) UIView *myUIView;
...

.m file
...
@synthesize myUIView;
...
// Get frame:
CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];

// Set up myUIView:
UIView *tempUIView = [[UIView alloc] initWithFrame:applicationFrame];
tempUIView.backgroundColor = [UIColor blackColor];
self.myUIView = tempUIView;
[tempUIView release];
...</code></pre>
<p>At this point in the code myUIView is now set up and ready to use. Because I used the setter to assign myUIView it is unaffected when I release tempUIView. If I had forgotten to use self.myUIView for the assignment then I would be unable to use myUIView later in the program.</p>
<p>Hope that clears things up for some of you. Please comment if I have something wrong or if you can help make things even clearer.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.musicalgeometry.com/archives/872/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>iPhone Camera Overlay App With Custom Button Example</title>
		<link>http://www.musicalgeometry.com/archives/821</link>
		<comments>http://www.musicalgeometry.com/archives/821#comments</comments>
		<pubDate>Fri, 11 Dec 2009 05:26:37 +0000</pubDate>
		<dc:creator>Jason Job</dc:creator>
				<category><![CDATA[AR]]></category>
		<category><![CDATA[XCode]]></category>
		<category><![CDATA[app]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[iPhone]]></category>

		<guid isPermaLink="false">http://www.musicalgeometry.com/?p=821</guid>
		<description><![CDATA[There seems to be a lot of interest recently in making apps that use a camera view with an overlay for augmented reality or what some might call pseudo-augmented reality applications (because often these apps just layer an image or &#8230; <a href="http://www.musicalgeometry.com/archives/821">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>There seems to be a lot of interest recently in making apps that use a camera view with an overlay for augmented reality or what some might call pseudo-augmented reality applications (because often these apps just layer an image or data on a camera view). I wasn&#8217;t satisfied with the few examples I found on the topic so I decided to try one myself. I will endeavour to make it as clear as I can and show you how to make a custom button while I am at it, but I do assume a basic knowledge of Objective-C and iPhone app development in Xcode.</p>
<div id="attachment_823" class="wp-caption alignnone" style="width: 210px"><a href="http://www.musicalgeometry.com/wp-content/uploads/2009/12/Screenshot-2009.12.10-18.46.38.png"><img class="size-medium wp-image-823 " style="border: 1px solid black;" title="Screenshot 2009.12.10 18.46.38" src="http://www.musicalgeometry.com/wp-content/uploads/2009/12/Screenshot-2009.12.10-18.46.38-200x300.png" alt="OverlayViewTester screenshot" width="200" height="300" /></a><p class="wp-caption-text">OverlayViewTester screenshot</p></div>
<p>So first I will describe the OverlayViewTester app. Basically it just overlays some cool looking red selection braces on a camera view and has a button that when pressed performs a &#8216;scan&#8217; for two seconds and lets you know by adding a &#8220;Scanning&#8230;&#8221; label at the top of the screen during that time. So really it does nothing, but it looks good and is a good first step to making a more fun and interesting interactive camera overlay app.</p>
<p>To get started download the source code from <a href="http://github.com/jj0b/OverlayViewTester">GitHub</a>. Next I will go through the files in the project and present the juicy bits. Consult the source code you downloaded for the full meal deal.</p>
<p><strong>OverlayViewTesterApDelegate</strong></p>
<p>Taking a look at the project we start with a typical app delegate, OverlayViewTesterAppDelegate which loads the OverlayViewController. Nothing monumental there so I won&#8217;t bother reproducing it here.</p>
<p><strong>OverlayViewController</strong></p>
<p>Now on to the OverlayViewController where we create the camera view.</p>
<p>In the interface, <em>OverlayViewController.h</em>: we define some constants:</p>
<pre><code>// Transform values for full screen support:
#define CAMERA_TRANSFORM_X 1
#define CAMERA_TRANSFORM_Y 1.12412

// iPhone screen dimensions:
#define SCREEN_WIDTH  320
#define SCREEN_HEIGTH 480</code></pre>
<p>In the implementation, <em>OverlayViewController.m</em> there is a bit of a GOTCHA. The line</p>
<pre><code>[self presentModalViewController:picker animated:YES];</code></pre>
<p>must be called in  <em>viewDidAppear:</em> not in a <em>viewDidLoad:</em> method. Here it is:</p>
<pre><code>- (void) viewDidAppear:(BOOL)animated {
    OverlayView *overlay = [[OverlayView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGTH)];

    // Create a new image picker instance:
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];

    // Set the image picker source:
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;

    // Hide the controls:
    picker.showsCameraControls = NO;
    picker.navigationBarHidden = YES;

    // Make camera view full screen:
    picker.wantsFullScreenLayout = YES;
    picker.cameraViewTransform = CGAffineTransformScale(picker.cameraViewTransform, CAMERA_TRANSFORM_X, CAMERA_TRANSFORM_Y);

    // Insert the overlay:
    picker.cameraOverlayView = overlay;

    // Show the picker:
    [self presentModalViewController:picker animated:YES];
    [picker release];

    [super viewDidAppear:YES];
}</code></pre>
<p>I think the comments make it clear what is going on there.</p>
<p><strong>OverlayView</strong></p>
<p>Next lets look at the custom subclass of UIView called OverlayView. This is where we actually create our overlay.</p>
<p>In the interface, <em>OverlayView.h</em> we declare two new methods:</p>
<pre><code>- (void)scanButtonTouchUpInside;
- (void)clearLabel:(UILabel *)label;</code></pre>
<p>Here are the important parts of the implementation, <em>OverlayView.m</em>:</p>
<pre><code>- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // Clear the background of the overlay:
	self.opaque = NO;
	self.backgroundColor = [UIColor clearColor];

	// Load the image to show in the overlay:
	UIImage *overlayGraphic = [UIImage imageNamed:@"overlaygraphic.png"];
	UIImageView *overlayGraphicView = [[UIImageView alloc] initWithImage:overlayGraphic];
	overlayGraphicView.frame = CGRectMake(30, 100, 260, 200);
	[self addSubview:overlayGraphicView];
	[overlayGraphicView release];

	ScanButton *scanButton = [[ScanButton alloc] initWithFrame:CGRectMake(130, 320, 60, 30)];

	// Add a target action for the button:
	[scanButton addTarget:self action:@selector(scanButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
	[self addSubview:scanButton];
    }
    return self;
}

- (void) scanButtonTouchUpInside {
    UILabel *scanningLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 50, 120, 30)];
    scanningLabel.backgroundColor = [UIColor clearColor];
    scanningLabel.font = [UIFont fontWithName:@"Courier" size: 18.0];
    scanningLabel.textColor = [UIColor redColor];
    scanningLabel.text = @"Scanning...";

    [self addSubview:scanningLabel];

    [self performSelector:@selector(clearLabel:) withObject:scanningLabel afterDelay:2];

    [scanningLabel release];
}

- (void)clearLabel:(UILabel *)label {
    label.text = @"";
}</code></pre>
<p>Notice that we have used an instance of ScanButton which we will get to next. When the ScanButton detects a UIControlEventTouchUpInside it calls the scanButtonTouchUpInside method which places a label on the screen for 2 seconds.</p>
<p><strong>ScanButton</strong></p>
<p>So finally we are left with our ScanButton. You might think that for a custom button we would subclass UIButton, but unless you really want to use the UIBUtton method setTitle:ForState it is recommended that you subclass UIControl. It will save you a world of hurt.</p>
<p>Here is the interface, <em>ScanButton.h</em>:</p>
<pre><code>#import &lt;Foundation/Foundation.h&gt;

@interface ScanButton : UIControl {
}

- (void)buttonPressed;

@end</code></pre>
<p>I put the buttonPressed method in here for future use. It is meant to be used to change things related to the button itself and not the actions associated with the button in the OverlayViewController. You could for example use it to have the button&#8217;s image or state or both toggle.</p>
<p>Last but not least we have the implementation, <em>ScanButton.m</em>:</p>
<pre><code>#import "ScanButton.h"

@implementation ScanButton

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
	// Set button image:
	UIImageView *buttonImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
	buttonImage.image = [UIImage imageNamed:@"scanbutton.png"];

	[self addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside]; // for future use

        [self addSubview:buttonImage];
    }
    return self;
}

- (void)buttonPressed {
    // TODO: Could toggle a button state and/or image
}

@end</code></pre>
<p>So there you have it. A custom camera overlay and a custom button. I hope that with this code you will be well on your way to writing much more useful, interesting and creative apps than this example. Happy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.musicalgeometry.com/archives/821/feed</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Retrieving JSON Data In iPhone Apps</title>
		<link>http://www.musicalgeometry.com/archives/571</link>
		<comments>http://www.musicalgeometry.com/archives/571#comments</comments>
		<pubDate>Sat, 15 Aug 2009 04:28:14 +0000</pubDate>
		<dc:creator>Jason Job</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[online]]></category>

		<guid isPermaLink="false">http://www.musicalgeometry.com/?p=571</guid>
		<description><![CDATA[As described at www.json.org, JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. The JSON format is one of two things; a list &#8230; <a href="http://www.musicalgeometry.com/archives/571">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>As described at <a href="http://www.json.org/">www.json.org</a>, JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. The JSON format is one of two things; a list of name/value pairs that can be realized as an object, record, struct, dictionary, hash table, keyed list, or associative array or an ordered list of values which in most languages is realized as an array, vector, list, or sequence.</p>
<div id="attachment_606" class="wp-caption alignnone" style="width: 170px"><a href="http://www.musicalgeometry.com/wp-content/uploads/2009/08/json160.gif"><img class="size-full wp-image-606 " style="border: 1px solid black;" title="json160" src="http://www.musicalgeometry.com/wp-content/uploads/2009/08/json160.gif" alt="JSON logo" width="160" height="160" /></a><p class="wp-caption-text">JSON logo</p></div>
<p>The JSON format is often used as an alternative to <a href="http://en.wikipedia.org/wiki/XML">XML</a> to transmit structured data over a network, its biggest use being in <a href="http://en.wikipedia.org/wiki/Ajax_(programming)">Ajax</a> web application programming.</p>
<p>Below are instructions for how to retrieve and parse JSON formatted data in an iPhone app.</p>
<p><strong>Adding JSON Framework To Your XCode Project</strong></p>
<p>To use JSON in an iPhone app you first need to download the JSON Framework for Objective-C from its <a href="http://code.google.com/p/json-framework/downloads/list">Google Code page</a>.</p>
<p>When it is downloaded, mount the DMG.</p>
<p>Finally, drag and drop the JSON directory onto the <em>Classes</em> folder icon in the <em>Groups &amp; Files</em> panel in XCode.</p>
<p><strong>Retrieving JSON Data</strong></p>
<p>First of all make sure that you include the JSON.h file in your implementaion(your .m file):</p>
<pre><code>#import "JSON.h"</code></pre>
<p>To retrieve JSON data use an NSURLConnection to issue an HTTP request. To do this you will need an <code>NSMutableData</code> variable to hold the response data. Create it in the interface (.h file) with:</p>
<pre><code>NSMutableData *responseData;</code></pre>
<p>and</p>
<pre><code>@property (nonatomic, retain) NSMutableData *responseData;</code></pre>
<p>and don&#8217;t forget to synthesize in the implementation (.m file):</p>
<pre><code>@synthesize responseData;</code></pre>
<p>Next you need to make an HTTP request with NSURLConnection so start by initializing responseData:</p>
<pre><code>responseData = [[NSMutableData data] retain];</code></pre>
<p>Then make the request:</p>
<pre><code>NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.someurl.com/somefile.json"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];</code></pre>
<p>Then you need to include the following methods to process the NSURLConnection and save the JSON data into the responseData variable:</p>
<pre><code>- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	[responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	label.text = [NSString stringWithFormat:@"Connection failed: %@", [error description]];
}</code></pre>
<p><strong>Making Use Of The JSON Data</strong></p>
<p>To make use of the JSON data use the connectionDidFinishLoading: method. Here is an example with some simple error checking:</p>
<pre><code>- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	[connection release];

	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	[responseData release];

	if ([responseString isEqualToString:@"\"Unable to find specified resource.\""]) {
		NSLog(@"Unable to find specified resource.\n");
	} else {
		NSDictionary *dictionary = [responseString JSONValue];
		self.someVariable = [dictionary valueForKey:@"somekey"];
	}
}</code></pre>
<p>In this connectionDidFinishLoading: method you can use any of the key names you know to be in the JSON data to get their values and store them or use them as you need.</p>
<p>Hopefully this helps you to get started using JSON data in your iPhone apps.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.musicalgeometry.com/archives/571/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Arduino 0017 Released</title>
		<link>http://www.musicalgeometry.com/archives/593</link>
		<comments>http://www.musicalgeometry.com/archives/593#comments</comments>
		<pubDate>Fri, 14 Aug 2009 18:10:47 +0000</pubDate>
		<dc:creator>Jason Job</dc:creator>
				<category><![CDATA[arduino]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[prototyping]]></category>

		<guid isPermaLink="false">http://www.musicalgeometry.com/?p=593</guid>
		<description><![CDATA[The latest version of the Arduino IDE has been released. From the arduino.cc website: &#8220;The open-source Arduino environment makes it easy to write code and upload it to the i/o board. It runs on Windows, Mac OS X, and Linux. The &#8230; <a href="http://www.musicalgeometry.com/archives/593">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://arduino.cc/en/Main/Software">latest version</a> of the Arduino IDE has been released.</p>
<div id="attachment_595" class="wp-caption alignnone" style="width: 260px"><a href="http://www.musicalgeometry.com/wp-content/uploads/2009/08/arduinoide.jpg"><img class="size-medium wp-image-595 " style="border: 1px solid black;" title="arduinoide" src="http://www.musicalgeometry.com/wp-content/uploads/2009/08/arduinoide-250x300.jpg" alt="Arduino IDE" width="250" height="300" /></a><p class="wp-caption-text">Arduino IDE</p></div>
<p>From the <a href="http://arduino.cc/">arduino.cc</a> website:</p>
<p>&#8220;The open-source Arduino environment makes it easy to write code and upload it to the i/o board. It runs on Windows, Mac OS X, and Linux. The environment is written in Java and based on Processing, avr-gcc, and other open source software.&#8221;</p>
<p>Arduino 0017 Release Notes:</p>
<pre><code>0017 - 2009.07.25

[documentation / examples]
* Many new and revised examples from Tom Igoe.

[core / libraries]
* Updated LiquidCrystal library by Limor Fried.  See reference for details.
* Updated Firmata library to version 2.1 (rev. 25).
* Replaced the Servo library with one (MegaServo) by Michael Margolis.
  Supports up to 12 servos on most Arduino boards and 48 on the Mega.
* Improving the accuracy of the baud rate calculations for serial
  communication (fixing double-speed problems on 8 MHz Arduino boards).
  Thanks to gabebear.

[environment]
* Synchronized with the Processing 1.0.3 code base (rev. 5503), bringing
  many improvements (listed below).
* New icons and about image by Thomas Glaser (envis precisely).
* Support for multiple sketch windows.
* The serial monitor now has its own window.
* Comment / Uncomment menu item (in Edit) and keyboard shortcut.
* Increase and Decrease Indent menu items (in Edit) and keyboard shortcuts.
* Support for third-party libraries in the SKETCHBOOK/libraries folder.
* Libraries are now compiled with the sketch, eliminating the delay when
  switching boards and the need to delete .o files when changing library
  source code.
* Arduino now comes as an app file (in a dmg) on the Mac.
* Adding the Arduino Nano w/ ATmega328 to the Tools &gt; Board menu.</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.musicalgeometry.com/archives/593/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How To Test For An Internet Connection On The iPhone</title>
		<link>http://www.musicalgeometry.com/archives/523</link>
		<comments>http://www.musicalgeometry.com/archives/523#comments</comments>
		<pubDate>Fri, 24 Jul 2009 03:41:57 +0000</pubDate>
		<dc:creator>Jason Job</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[iPhone]]></category>

		<guid isPermaLink="false">http://www.musicalgeometry.com/?p=523</guid>
		<description><![CDATA[If you write an app that uses the internet then the Apple Human Interface Guidelines require that you check for a WiFi or Wireless Wide Area Network (cellular) connection and let the user know if they are not available. One &#8230; <a href="http://www.musicalgeometry.com/archives/523">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>If you write an app that uses the internet then the Apple Human Interface Guidelines require that you check for a WiFi or Wireless Wide Area Network (cellular) connection and let the user know if they are not available.</p>
<div id="attachment_538" class="wp-caption alignnone" style="width: 210px"><a href="http://www.musicalgeometry.com/wp-content/uploads/2009/07/nofunctionscreen.jpg"><img class="size-medium wp-image-538 " style="border: 1px solid black;" title="nofunctionscreen" src="http://www.musicalgeometry.com/wp-content/uploads/2009/07/nofunctionscreen-200x300.jpg" alt="nofunctionscreen" width="200" height="300" /></a><p class="wp-caption-text">iTunes app with no WiFi</p></div>
<p>One reliable and easy way to test for this is to make use of the code in the Reachability sample project that Apple provides with XCode. Here is what you need to do:</p>
<ol>
<li>Add Reachability.h and Reachability.m from the sample project to your project</li>
<li>Add the SystemConfiguration.framework to your project</li>
<li>Use the following code in your project:</li>
</ol>
<pre><code>[[Reachability sharedReachability] setHostName:@"www.apple.com"];
NetworkStatus internetStatus = [[Reachability sharedReachability] remoteHostStatus];
if ((internetStatus != ReachableViaWiFiNetwork) &amp;&amp; (internetStatus != ReachableViaCarrierDataNetwork)) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Internet Connection"
        message:@"An internet connection via WiFi or cellular network is needed to use this app."
        delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
    [alert show];
    [alert release];
} else {
    // do whatever your program does
}</code></pre>
<p>In the first line you can set setHostName: to whatever you like. A simple page on your server that just returns True works just fine.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.musicalgeometry.com/archives/523/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Software Debouncing Multiple Latching Switches With Arduino</title>
		<link>http://www.musicalgeometry.com/archives/248</link>
		<comments>http://www.musicalgeometry.com/archives/248#comments</comments>
		<pubDate>Mon, 12 Jan 2009 06:29:57 +0000</pubDate>
		<dc:creator>Jason Job</dc:creator>
				<category><![CDATA[MIDI]]></category>
		<category><![CDATA[arduino]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[make]]></category>
		<category><![CDATA[prototyping]]></category>

		<guid isPermaLink="false">http://www.musicalgeometry.com/?p=248</guid>
		<description><![CDATA[This last week I have been working on making the operation of my MIDI controller prototype more robust. One of my tasks has been to debounce and latch the states of my pushbutton toggle switches. Though you could use hardware &#8230; <a href="http://www.musicalgeometry.com/archives/248">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>This last week I have been working on making the operation of my MIDI controller prototype more robust. One of my tasks has been to debounce and latch the states of my pushbutton toggle switches. Though you could use hardware for debouncing and latching I chose to do it with software. Doing it this way is cheaper, requires less space on a PCB and is fairly easily accomplished with todays microcontrollers.</p>
<div class="wp-caption alignnone" style="width: 510px"><a href="http://www.flickr.com/photos/musicalgeometry/3763763709/"><img class=" " style="border: 1px solid black;" title="A lone pushbutton switch" src="http://farm3.static.flickr.com/2436/3763763709_400e22d74e.jpg" alt="A lone pushbutton switch" width="500" height="375" /></a><p class="wp-caption-text">A lone pushbutton switch</p></div>
<p>Before setting out to debounce my pushbuttons I did some searching on Google and discovered an excellent article on debouncing called simply, <a href="http://www.ganssle.com/debouncing.pdf">A Guide To Debouncing</a>. It covers multiple techniques for both hardware and software debouncing.</p>
<p>After reading the article, I decided to go with a software counting algorithm. I did some more research but I wasn&#8217;t happy with the examples that I found. All of them involved debouncing a single switch. I wanted to debounce an entire port of switches. To do this you could just repeat the debouncing code for each switch but I decided to write a single piece of code to handle an entire port.</p>
<p>Below is my solution using PORTB on an Arduino. PORTB is a six pin port. This could easily be ported to be used on any AVR microcontroller or indeed any other microcontroller that can be programmed in C.</p>
<div class="wp-caption alignnone" style="width: 510px"><a href="http://www.flickr.com/photos/musicalgeometry/3763762659/"><img class="  " style="border: 1px solid black;" title="Arduino NG" src="http://farm4.static.flickr.com/3523/3763762659_6df9ff15c7.jpg" alt="Arduino NG" width="500" height="375" /></a><p class="wp-caption-text">My Arduino NG</p></div>
<p>All the pushbuttons in my example are active high with pull down resistors. The code could easily be adapted for active low. (Note that my prototype actually only has two buttons connected to it. I set up wires with pull downs to act as switches for the remaining pins)</p>
<p>First we define the number of switches on our port (in this case six), then the debounce depth. Debounce depth is the number of consecutive times that a switch must be read to have a certain value (HIGH or LOW, 1 or 0) before a press of that switch is validated.</p>
<pre><code>#define numButtons 6
#define debounceDepth 10</code></pre>
<p>Next we set up the variables we will need. The first one is used to read the PORTB value into. The second is to keep a memory of the last debounceDepth number of reads. The next keeps tabs on whether the pushbutton switch has been released after pressing. This variable provides a form of hysterisis so that we don&#8217;t get multiple toggles on one button press. The buttonPressFilter is a bitwise ANDed sum of all of the debounceDepth number of memories. The result in the buttonPressFilter is what determines if a pushbutton switch has been validly pressed.</p>
<pre><code>char buttonRead;
char buttonMemory[debounceDepth] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int buttonHasReleased[numButtons] = {true,true,true,true,true,true};
char buttonPressFilter = 0xFF;
int buttonState[numButtons] = {0,0,0,0,0,0};</code></pre>
<p>So that is the end of initialization. Now onto the code that you would put in your loop. The buttonPressFilter is an 8-bit variable with each of the lower 6 bits representing the state of a pushbutton switch, pressed or not-pressed. (Remember, PORTB on Arduino only has 6 pins) Each time we loop through here, we reset the buttonPressFilter to start as all 1&#8242;s. As it is bitwise ANDed with the previous button memories, any button read of a zero value will fall through as a zero, the rest will be left as 1&#8242;s. It basically &#8216;filters&#8217; out any button presses that are not yet stable.</p>
<pre><code>buttonPressFilter = 0xFF;</code></pre>
<p>Here we shift all the memory by one, dumping the oldest reading to make room for the new reading. Then we AND all the old memories together.</p>
<pre><code>for(i=(debounceDepth-1); i&gt;0; i--) {
    buttonMemory[i] = buttonMemory[i-1];
    buttonPressFilter &amp;= buttonMemory[i];
}</code></pre>
<p>Here we read the current status of the switches on PORTB.</p>
<pre><code>buttonRead = PINB;</code></pre>
<p>Now for each pushbutton switch we check if the current read indicates a press. If it does, then we set its memory bit, otherwise we clear it.</p>
<pre><code>for(i=0; i&lt;numButtons; i++) {
    if((buttonRead &amp; bitMask[i]) != 0) { // if current read shows button is pressed
        buttonMemory[0] |= bitMask[i];     // set the memory bit for that button
    } else {
        buttonMemory[0] &amp;= ~(bitMask[i]); // otherwise clear the memory bit for that button
    }
}</code></pre>
<p>Take account of the newest read into memory.</p>
<pre><code>buttonPressFilter &amp;= buttonMemory[0]; // AND the final memory bits into the buttonPressFilter</code></pre>
<p>Now the buttonPressFilter contains the current pressed or non-pressed state of the switches. If any switch has had a consistent value for debounceDepth number of times, then toggle the state in the buttonState array and do whatever it is you want your button to do.</p>
<pre><code>for(i=0; i&lt;numButtons; i++) {
    if((buttonPressFilter &amp; bitMask[i]) != 0) {
        if(buttonHasReleased[i] == true) {
            if(buttonState[i] == 0) {
                // ENTER CODE HERE FOR WHAT YOU WANT TO HAPPEN WHEN BUTTON IS ON
                buttonState[i] = 1;
            } else {
                // ENTER CODE HERE FOR WHAT YOU WANT TO HAPPEN WHEN BUTTON IS OFF
                buttonState[i] = 0;
            }
        }
        buttonHasReleased[i] = false;
    } else {
        buttonHasReleased[i] = true;
    }
}</code></pre>
<p>One final thing to mention is that the debounceDepth value is something that you need to experiment with for the specific switches in your project. Currently with my cheap pushbuttons sitting in a cardboard chassis and wired to a breadboard, I need a value of 10 to get stable results. Using better switches, a stable chassis and a PCB I expect this number to drop.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.musicalgeometry.com/archives/248/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
