<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[Adoption Curve Dot Net]]></title>
  <link href="http://adoptioncurve.net/atom.xml" rel="self"/>
  <link href="http://adoptioncurve.net/"/>
  <updated>2016-06-25T17:11:34+01:00</updated>
  <id>http://adoptioncurve.net/</id>
  <author>
    <name><![CDATA[Tim Duckett]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[Collection View Updates in iOS10 Part 2]]></title>
    <link href="http://adoptioncurve.net/archives/2016/06/collection-view-updates-in-ios10-part-2"/>
    <updated>2016-06-25T16:39:25+01:00</updated>
    <id>http://adoptioncurve.net/archives/2016/06/collection-view-updates-in-ios10-part-2</id>
    <content type="html"><![CDATA[<p>Along with <a href="https://adoptioncurve.net/archives/2016/06/collection-view-updates-in-ios10/">prefetching</a>, many of the other changes to <code>UICollectionView</code> introduced with iOS10 relate to performance improvements.</p>

<p>The lifecycle of a cell has been well-established since <code>UICollectionView</code> was introduced in iOS6:</p>

<p><em><code>prepareForReuse</code></em> is called first, and is where the cell&rsquo;s contents should be set back to their default state</p>

<p><em><code>cellForItemAtIndexPath:</code></em> is where the majority of the work involved in setting up the cell takes place</p>

<p><em><code>willDisplayCell:</code></em> is a last-minute opportunity to update the cell before it&rsquo;s displayed</p>

<p><em><code>didEndDisplayingCell:</code></em> is called as the cell disappears from view</p>

<p>The four lifecycle functions remain in iOS10, but there have been some subtle changes to <em>when</em> they&rsquo;re called:</p>

<ul>
<li><code>willDisplayCell:</code> is now called later than previously - whereas in iOS9 and earlier the function was called immediately the cell was taken off the recycle queue, in 10 it&rsquo;s not called until just before the cell is displayed</li>
<li>previously, <code>didEndDisplayingCell</code> was called as soon as the cell scrolled out of the visible bounds of the collection view. Now there&rsquo;s a delay, which means that the cell hangs around a bit longer in case it&rsquo;s scrolled back in again. This removes the need to recreate the cell from scratch, and should improve performance when changing scroll direction.</li>
</ul>


<p>The other significant change is that cells are now dequeued individually rather than row-by-row.  This helps to spread out the load of setting each cell up, rather than causing spikes in load; and also aids with making sure that cells are always ready to be displayed.</p>

<p>The good news is that all these changes take place under the hood, so you don&rsquo;t need to make changes to pre-existing code in order to take advantage of them.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Collection View Updates in iOS10, Part 1]]></title>
    <link href="http://adoptioncurve.net/archives/2016/06/collection-view-updates-in-ios10"/>
    <updated>2016-06-25T14:34:26+01:00</updated>
    <id>http://adoptioncurve.net/archives/2016/06/collection-view-updates-in-ios10</id>
    <content type="html"><![CDATA[<p>Following WWDC, iOS 10 is now out in beta form ahead of a probable release in the autumn. There are a whole load of brand-new features, but also some tweaks to existing ones, and UICollectionView is no exception.</p>

<p>Although UICollectionView is a highly-performant control, Apple haven&rsquo;t let it stand still. One of the most interesting new features is designed to improve the performance of collection views with expensive data sources.</p>

<h2>Background</h2>

<p>The aim for any iOS application is to run the UI at the full 60 frames per second, to deliver a completely smooth scrolling performance. Any frame rate significantly lower than this will manifest itself by dropped frames and stuttery performance.</p>

<p>60fps equates to 16.67ms per frame, which isn&rsquo;t long if you&rsquo;re dealing with drawing collection view cells using data from slow sources. The trick to high performance collecion views is to get the <code>cellForItemAtIndexPath</code> to return a cell as fast as possible, but this can be difficult. Techniques like asynchronous fetching of images can help, but these aren&rsquo;t a miracle cure.</p>

<blockquote><p>Note: This technique is also available to use with <code>UITableView</code> - just replace references to <code>UICollectionView</code> with <code>UITableView</code>, and the implementation patterns are identical.</p></blockquote>

<h2>Prefetching</h2>

<p>In iOS10, Apple have introduced a new <code>UICollectionViewDataSource</code> protocol extension called <code>UICollectionViewDataSourcePrefetching</code>.</p>

<p>This introduces a new property on <code>UICollectionView</code> called <code>prefetchDataSource</code>.  This is a class that implements two <code>UICollectionViewDataSourcePrefetching</code> protocol functions:</p>

<ul>
<li><p><code>collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath])</code></p></li>
<li><p><code>collectionView(_ collectionView: UICollectionView, cancelPrefetchingForItemsAt indexPaths: [IndexPath])</code></p></li>
</ul>


<p>The <code>prefetchItemsAt indexPaths:</code> function is called by the collection view when it looks like the scrolling rate of the collection view will outstrip the ability of <code>cellForItemAtIndexPath</code> to deliver cells in a timely manner.</p>

<p>The collection view passes in an <code>Array</code> of <code>NSIndexPaths</code> for cells that are likely to be needed in the future. This gives you an opportunity to update the data source that underlies the collection view.  For example, if your data source was an <code>Array</code> of images, you could call out to the network to download the images and insert them into the data source so that they are ready to be used by the <code>cellForRowAtIndexPath</code> function.</p>

<p>The second method is normally called when the scrolling direction changes. The reasoning for this is that you&rsquo;re likely to be prefetching data well in advance of the cells being displayed - if those cells won&rsquo;t now get displayed because the collection view is scrolling away from them, you may as well cancel whatever operation it is that you&rsquo;re carrying out to update the data source.  Again, the index paths of the cells in question are passed in as an <code>Array</code> of <code>NSIndexPaths</code>.</p>

<h2>Implementing pre-fetching</h2>

<p>To take advantage of the new prefetch feature, you&rsquo;ll need to do four things:</p>

<ul>
<li>Conform a class to the <code>UICollectionViewDataSourcePrefetching</code> protocol</li>
<li>Implement the <code>collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath])</code> function to update the collection view&rsquo;s <code>dataSource</code></li>
<li>Optionally, implement the <code>collectionView(_ collectionView: UICollectionView, cancelPrefetchingForItemsAt indexPaths: [IndexPath])</code> function to cancel any in-flight prefetching operations</li>
<li>Set the conforming class as the <code>collectionView</code>&rsquo;s <code>prefetchDataSource</code> property.</li>
</ul>


<h3>Conforming to <code>UICollectionViewDataSourcePrefetching</code></h3>

<p>This isn&rsquo;t difficult: just mark your data source as implementing the protocol:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>class MyViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDataSourcePrefetching {
</span><span class='line'>  ...
</span><span class='line'>}</span></code></pre></td></tr></table></div></figure>


<h3>Implementing prefetching</h3>

<p>Prefetching is implementing with the <code>collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath])</code> function. There the collection view passes in an <code>Array</code> of <code>NSIndexPaths</code>, one for each of the cells that are likely to be displayed.</p>

<p>Your job here is to iterate across this array, and update the collection view&rsquo;s data source accordingly:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
</span><span class='line'>
</span><span class='line'>    for indexPath in indexPaths {
</span><span class='line'>      
</span><span class='line'>      ... expensive operation to retrieve some data...
</span><span class='line'>      
</span><span class='line'>        dataArray[indexPath.row] = retrievedData
</span><span class='line'>      
</span><span class='line'>    }
</span><span class='line'>    
</span><span class='line'>}</span></code></pre></td></tr></table></div></figure>


<p>There are a couple of important points to note here: the first is that you&rsquo;re <em>only</em> updating the collection view&rsquo;s underlying data source - not returning any data directly.  This could be as simple as updating an <code>Array</code> of strings (as above), or more complex like updating a CoreData or Realm model.</p>

<p>The second point to bear in mind is that after the prefetch has taken place, there&rsquo;s no guarantee when, or if, that retrieved will be used. The collection view&rsquo;s scroll rate could slow down; or the direction reverse entirely.</p>

<p>For this reason, there is a chance that time-critical data could be stale by the time it&rsquo;s displayed. Whether this is a factor that you need to consider will of course depend on the nature of the data being displayed.</p>

<h3>Implenting prefetch cancellation</h3>

<p>To an extent, requests for prefetches are a bit of a guess - the collection view is attempting to optimise for an uncertain future state that might not actually come to pass.  For example, if the scroll rate slows, or reverses altogether, there&rsquo;s a chance that the cells for which prefetch has been requested may never actually be displayed.</p>

<p>In this situation, any inflight prefetch would be wasted effort. Rather than make redundant requests, the <code>UICollectionViewDataSourcePrefetch</code> protocol defines a function to cancel outstanding requests: <code>collectionView(_ collectionView: UICollectionView, cancelPrefetchingForItemsAt indexPaths: [IndexPath])</code></p>

<p>This is called if the collection view decides that prefetching would be over-optimisation - it passes an <code>Array</code> of <code>NSIndexPaths</code> as the function&rsquo;s parameter, and it&rsquo;s up to you to iterate over those and cancel any requests where it makes sense to do so.</p>

<h3>Hooking up the prefetch delegate to the collection view</h3>

<p>With the class conforming to the protocol, and with one or both of the functions implemented, you need to add it as a <code>prefetchDataSource</code> to the collection view.</p>

<p>This is as simple as updating the property (here, we&rsquo;re assuming that the collection view controller is acting as its own <code>prefetchDataSource</code>):</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>collectionView.prefetchDataSource = self</span></code></pre></td></tr></table></div></figure>


<p>This has to be done <em>before</em> any calls to any of the <code>UICollectionViewDataSource</code> protocol functions, so it probably makes sense to do so at the same time as setting up the collection view&rsquo;s other properties, such as cell registration.</p>

<h2>Conclusion</h2>

<p><code>UICollectionView</code> is a high-performance control to begin with, with a significant amount of &lsquo;under the hood&rsquo; optimisation going on that we don&rsquo;t see. Prefetching is another tool to eke out even more performance, especially in situations where getting the source data for display in collection view cells is expensive or slow.</p>

<p>However, there&rsquo;s a saying that &ldquo;premature optimisation is the root of all evil&rdquo; in code, so it&rsquo;s not a magic bullet. And don&rsquo;t overlook the fact that often the most expensive part of the process is compositing the collection view cell itself. But if you&rsquo;re looking to squeeze out the last drops of performance to make your collection views as smooth as possible, prefetching may be worth a try.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Testing Asynchronous Code in Swift]]></title>
    <link href="http://adoptioncurve.net/archives/2015/10/testing-asynchronous-code-in-swift"/>
    <updated>2015-10-02T20:28:25+01:00</updated>
    <id>http://adoptioncurve.net/archives/2015/10/testing-asynchronous-code-in-swift</id>
    <content type="html"><![CDATA[<p>Asynchronous code is both hard to test; and important to test.</p>

<p>It&rsquo;s important, because it often handles some of the most critical and yet unreliable parts of an app - in other words, networking.</p>

<p>It&rsquo;s hard because it&rsquo;s, well, asynchronous. One of the two jokes in software engineering goes something like &ldquo;Some people, when faced with a problem, think &lsquo;I know, I&rsquo;ll use threading&rsquo;. Now problems have two they.&rdquo;</p>

<p>The standard rhythm of a unit test goes like this:</p>

<ul>
<li>set up the preconditions for the test, to get the system into a known state</li>
<li>make some assertions about what result you&rsquo;re looking for</li>
<li>fire the functions under test</li>
<li>verify that the assertions were met</li>
</ul>


<p>The problem with asynchronous code is that the third and final steps don&rsquo;t always come in that order, particularly if you&rsquo;re attemping to test a long-running operation. It can still be churning away as your verification takes place - and your tests are unlikely to pass in that kind of scenario.</p>

<p>Fortunately, there are ways around this. It&rsquo;s not especially pretty, but it does work.</p>

<h2>waitForExpectations</h2>

<p>The key to testing async code in Swift is using the <code>waitForExpectationWithTimeout</code> feature of the <code>XCTest</code> framework.  An expectation in this context is just a flag that tells the test code &ldquo;I&rsquo;m done, you can check your assertions now&rdquo;.</p>

<p>The expectation will hang around and wait for the fulfillment message, which gives the async code a chance to complete before the assertions are checked.</p>

<p>There are three stages involved in setting this up:</p>

<ul>
<li>Creating an expectation</li>
<li>Calling the async function, and then flagging that the expection has been fulfilled when your code has comepleted</li>
<li>Wrapping the assertions inside a <code>waitForExpectationWithTimeout block</code> so that they will wait for the fulfillment to occor.</li>
</ul>


<h3>Creating the expectation</h3>

<p>This is quite simple. At the top of your test function, create an expectation with</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='swift'><span class='line'><span class="k">let</span> <span class="n">asyncExpectation</span> <span class="o">=</span> <span class="n">expectationWithDescription</span><span class="p">(</span><span class="s">&quot;longRunningFunction&quot;</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>This needs to be done <em>before</em> you call the async code.</p>

<h3>Fulfilling the expectation</h3>

<p>With the expectation created, you need to signal that it&rsquo;s fulfilled after your asynchronous code completes. Here&rsquo;s an example of a function that fires off a network request, and takes a completion handler as a parameter to process the data that&rsquo;s returned:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='swift'><span class='line'><span class="k">func</span> <span class="n">networkManager</span><span class="p">.</span><span class="n">getDataFromApiForUser</span><span class="p">(</span><span class="nl">user</span><span class="p">:</span> <span class="n">User</span><span class="p">,</span> <span class="nl">completionHandler</span><span class="p">:</span> <span class="p">(</span><span class="nl">userData</span><span class="p">:</span> <span class="bp">NSData</span><span class="o">?</span><span class="p">,</span> <span class="nl">error</span><span class="p">:</span> <span class="bp">NSError</span><span class="o">?</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="p">()</span> <span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>In normal situations, you&rsquo;d use this function with something like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='swift'><span class='line'><span class="n">networkManager</span><span class="p">.</span><span class="n">getDataFromApiForUser</span><span class="p">(</span><span class="n">testUser</span><span class="p">,</span> <span class="nl">completionHandler</span><span class="p">:</span> <span class="p">{</span> <span class="p">(</span><span class="n">userData</span><span class="p">,</span> <span class="n">error</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="p">()</span> <span class="k">in</span>
</span><span class='line'>  
</span><span class='line'>  <span class="p">...</span> <span class="n">handle</span> <span class="n">the</span> <span class="n">error</span> <span class="k">if</span> <span class="n">one</span> <span class="n">occurs</span>
</span><span class='line'>  <span class="p">...</span>
</span><span class='line'>  <span class="p">...</span> <span class="n">otherwise</span> <span class="n">process</span> <span class="n">the</span> <span class="n">userData</span> <span class="n">object</span>
</span><span class='line'>  
</span><span class='line'><span class="p">)}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Testing the function in a unit test is very similar:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='swift'><span class='line'><span class="n">networkManager</span><span class="p">.</span><span class="n">getDataFromApiForUser</span><span class="p">(</span><span class="n">testUser</span><span class="p">,</span> <span class="nl">completionHandler</span><span class="p">:</span> <span class="p">{</span> <span class="p">(</span><span class="n">userData</span><span class="p">,</span> <span class="n">error</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="p">()</span> <span class="k">in</span>
</span><span class='line'>
</span><span class='line'>  <span class="p">...</span> <span class="n">handle</span> <span class="n">the</span> <span class="n">error</span> <span class="k">if</span> <span class="n">one</span> <span class="n">occurs</span>
</span><span class='line'>  <span class="p">...</span>
</span><span class='line'>  <span class="p">...</span> <span class="n">otherwise</span> <span class="n">process</span> <span class="n">the</span> <span class="n">userData</span> <span class="n">object</span>
</span><span class='line'>
</span><span class='line'>  <span class="n">expectation</span><span class="p">.</span><span class="n">fulfill</span><span class="p">()</span>
</span><span class='line'>  
</span><span class='line'><span class="p">)}</span>
</span></code></pre></td></tr></table></div></figure>


<p>The key difference is that last line - <code>expectation.fulfill()</code>. What we&rsquo;re doing here is to signal to the <code>asyncExpectation</code> that everything is completed, and it&rsquo;s now safe to check the assertions.</p>

<h3>Checking the assertions</h3>

<p>Assertions in this context are just the usual <code>XCTest</code> assertions that you&rsquo;ll already be familar with. What&rsquo;s different is that we wrap them in a <code>waitForExpectationsWithTimeout</code> block:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='swift'><span class='line'><span class="nb">self</span><span class="p">.</span><span class="n">waitForExpectationsWithTimeout</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span> <span class="p">{</span> <span class="n">error</span> <span class="k">in</span>
</span><span class='line'>  
</span><span class='line'>  <span class="n">XCTestAssertNil</span><span class="p">(</span><span class="n">error</span><span class="p">,</span> <span class="s">&quot;Something went horribly wrong&quot;</span><span class="p">)</span>
</span><span class='line'>  <span class="n">XCTestAssertEqual</span><span class="p">(</span><span class="n">testUser</span><span class="p">.</span><span class="n">orders</span><span class="p">.</span><span class="n">count</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>
</span><span class='line'>  
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>This function will do two things - firstly, it will wait for a maximum of five seconds before giving up and failing. This prevents you from locking up the tests in an infinite loop if something goes wrong with the code under test. How long to wait is dependent on the kind of processing that&rsquo;s taking place - but ideally shouldn&rsquo;t be so long that it locks up the test suite unncessarily.</p>

<p>Secondly, it will fire the <code>XCTest</code> expectations as soon as the <code>expectation.fulfill()</code> function is called.  By triggering that at the end of the chunk of async code, you&rsquo;re preventing the assertions racing away and being checked before the function under test has had a chance to complete.</p>

<h3>Putting it all together</h3>

<p>Putting that all together in a example test looks like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
</pre></td><td class='code'><pre><code class='swift'><span class='line'><span class="k">func</span> <span class="nf">testUserOrdersAreRetrievedFromApiAndProcessed</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">let</span> <span class="n">asyncExpectation</span> <span class="o">=</span> <span class="n">expectationWithDescription</span><span class="p">(</span><span class="s">&quot;longRunningFunction&quot;</span><span class="p">)</span>
</span><span class='line'>  
</span><span class='line'>  <span class="k">let</span> <span class="n">testUser</span> <span class="o">=</span> <span class="n">User</span><span class="p">.</span><span class="n">initWithName</span><span class="p">(</span><span class="s">&quot;Foo&quot;</span> <span class="nl">andAccountNumber</span><span class="p">:</span> <span class="mi">1234</span><span class="p">)</span>
</span><span class='line'>  
</span><span class='line'>  <span class="n">networkManager</span><span class="p">.</span><span class="n">getDataFromApiForUser</span><span class="p">(</span><span class="n">testUser</span><span class="p">,</span> <span class="nl">completionHandler</span><span class="p">:</span> <span class="p">{</span> <span class="p">(</span><span class="n">userData</span><span class="p">,</span> <span class="n">error</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="p">()</span> <span class="k">in</span>
</span><span class='line'>      
</span><span class='line'>      <span class="p">...</span> <span class="n">handle</span> <span class="n">the</span> <span class="n">error</span> <span class="k">if</span> <span class="n">one</span> <span class="n">occurs</span>
</span><span class='line'>      <span class="p">...</span>
</span><span class='line'>      <span class="p">...</span> <span class="n">otherwise</span> <span class="n">process</span> <span class="n">the</span> <span class="n">userData</span> <span class="n">object</span>
</span><span class='line'>      
</span><span class='line'>      <span class="n">expectation</span><span class="p">.</span><span class="n">fulfill</span><span class="p">()</span>
</span><span class='line'>      
</span><span class='line'>  <span class="p">)}</span>
</span><span class='line'>  
</span><span class='line'>  <span class="nb">self</span><span class="p">.</span><span class="n">waitForExpectationsWithTimeout</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span> <span class="p">{</span> <span class="n">error</span> <span class="k">in</span>
</span><span class='line'>      
</span><span class='line'>      <span class="n">XCTestAssertNil</span><span class="p">(</span><span class="n">error</span><span class="p">,</span> <span class="s">&quot;Something went horribly wrong&quot;</span><span class="p">)</span>
</span><span class='line'>      <span class="n">XCTestAssertEqual</span><span class="p">(</span><span class="n">testUser</span><span class="p">.</span><span class="n">orders</span><span class="p">.</span><span class="n">count</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>
</span><span class='line'>      
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>It&rsquo;s not the cleanest looking test code you&rsquo;ll ever write, especially if you&rsquo;re not a fan of the <code>Junit</code>-style syntax of the <code>XCTest</code> framework - but it works. And given how important asynchronous code like network requests or long-running processing tends to be to an app, it&rsquo;s worth sacrificing a little style for the reassurance that high test coverage will provide.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Mocks and Expectations With Swift]]></title>
    <link href="http://adoptioncurve.net/archives/2015/09/mocks-and-expectations-with-swift"/>
    <updated>2015-09-30T20:41:02+01:00</updated>
    <id>http://adoptioncurve.net/archives/2015/09/mocks-and-expectations-with-swift</id>
    <content type="html"><![CDATA[<p>A new language, a new way of doing things - including testing. One of the harder parts of getting to grips with Swift has been figuring out how testing works, and in particular how to do more extensive stuff like mocking and stubbing.</p>

<p>By way of background, mocking is the art of creating &ldquo;stunt doubles&rdquo; for your classes that are involved in tests. You&rsquo;d do this for a couple of reasons - either to manipulate your stunt doubles into a known state for testing purpose; or because it&rsquo;s expensive or difficult to use the real thing.</p>

<p>An example of this might be testing what happens if a network service doesn&rsquo;t return the result that you were expecting. If you&rsquo;re testing the use of a live service, it might be tricky to create a deliberate failure just for testing purposes. Far easier to create a stunt double and use this to return the value that your tests require.</p>

<p>The other situation where you may want a stand-in object is if you want to verify that a method has been called. Say for example you&rsquo;ve got some kind of callback, and you want to test whether this gets fired. By setting an expectation on the callback method, you can verify that it actually was called - which is especially useful if you&rsquo;re testing asynchronous operations.</p>

<p>It was perfectly possible to do all of this in Objective-C, but it required the use of external libraries such as OCMock or Kiwi. Swift, on the other hand, is much easier. The structure of the language makes it very straight-forward to implement basic mocking and stubbing operations, without the need for external pods or libraries.</p>

<p>Here&rsquo;s an example. Say we have a class called <code>SooperClass</code>, and this has a function called <code>someExpensiveFunctionThatReturnsAStringFromTheWeb</code>. We don&rsquo;t want to <em>really</em> fire this as part of our tests, because (for the sake of this example) we get charged every time we make an API call. Instead, we need to mock it.</p>

<p>The first step is to create a mock of <code>SooperClass</code> inside our test class.  At the top of the test class, create a <code>FakeSooperClass</code> which inherits from <code>SooperClass</code> like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='swift'><span class='line'><span class="k">class</span> <span class="nl">MockrTests</span><span class="p">:</span> <span class="n">XCTestCase</span> <span class="p">{</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">class</span> <span class="nl">FakeSooperClass</span><span class="p">:</span> <span class="n">SooperClass</span> <span class="p">{</span>
</span><span class='line'>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="p">...</span> <span class="n">rest</span> <span class="n">of</span> <span class="n">the</span> <span class="n">test</span> <span class="k">class</span> <span class="n">here</span> <span class="p">...</span>
</span><span class='line'>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Next, override the method that you want to test:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='swift'><span class='line'><span class="k">class</span> <span class="nl">FakeSooperClass</span><span class="p">:</span> <span class="n">SooperClass</span> <span class="p">{</span>
</span><span class='line'>
</span><span class='line'>    <span class="kr">override</span> <span class="k">func</span> <span class="n">someExpensiveFunctionThatReturnsAStringFromTheWeb</span><span class="p">()</span> <span class="o">-&gt;</span> <span class="n">String</span> <span class="p">{</span>
</span><span class='line'>  
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>And use this overridden method to return whatever data your test needs:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='swift'><span class='line'><span class="kr">override</span> <span class="k">func</span> <span class="n">someExpensiveFunctionThatReturnsAStringFromTheWeb</span><span class="p">()</span> <span class="o">-&gt;</span> <span class="n">String</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">return</span> <span class="s">&quot;Finally! Some content!&quot;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now you can use this in your test:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='swift'><span class='line'><span class="k">func</span> <span class="nf">testThatTheExpensiveFunctionReturnsSomethingUseful</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">let</span> <span class="n">fakeSooperClass</span> <span class="o">=</span> <span class="n">FakeSooperClass</span><span class="p">()</span>
</span><span class='line'>    <span class="k">let</span> <span class="n">stringFromTheWeb</span> <span class="o">=</span> <span class="n">fakeSooperClass</span><span class="p">.</span><span class="n">someExpensiveFunctionThatReturnsAStringFromTheWeb</span><span class="p">()</span>
</span><span class='line'>
</span><span class='line'>  <span class="p">...</span> <span class="n">use</span> <span class="n">the</span> <span class="n">value</span> <span class="k">in</span> <span class="n">the</span> <span class="n">rest</span> <span class="n">of</span> <span class="n">the</span> <span class="n">test</span> <span class="p">...</span>
</span><span class='line'>  
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Here, we&rsquo;ve created a mock instance of <code>SooperClass</code>, and used this to return data in the format that we need for the rest of the test. But in doing so, we haven&rsquo;t had to call out to the public API that <code>SooperClass</code> would normally talk to.</p>

<p>We can take the fake class one step further, and test that the method actually gets called. We&rsquo;ll set an <em>expectation</em> that the function will be called once during the code that we&rsquo;re testing - if it isn&rsquo;t, something has gone wrong somewhere.</p>

<p>To do this, we need to extend our fake class slightly, to include a flag:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='swift'><span class='line'><span class="k">class</span> <span class="nl">FakeSooperClass</span><span class="p">:</span> <span class="n">SooperClass</span> <span class="p">{</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">var</span> <span class="n">didCallExpensiveFunctionFlag</span> <span class="o">=</span> <span class="nb">false</span>
</span><span class='line'>
</span><span class='line'>    <span class="kr">override</span> <span class="k">func</span> <span class="n">someExpensiveFunctionThatReturnsAStringFromTheWeb</span><span class="p">()</span> <span class="o">-&gt;</span> <span class="n">String</span> <span class="p">{</span>
</span><span class='line'>        <span class="k">return</span> <span class="s">&quot;Finally! Some content!&quot;</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>This flag is initially false (because the function hasn&rsquo;t been called yet). When the function <em>is</em> called, we&rsquo;ll flip the flag inside the fake class. By getting the test to check the state of the flag, it will be possible to see if the function was called as we expected.</p>

<p>This needs a tweak to our fake <code>someExpensiveMethodThatReturnsAStringFromTheWeb()</code> function:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='swift'><span class='line'><span class="k">class</span> <span class="nl">FakeSooperClass</span><span class="p">:</span> <span class="n">SooperClass</span> <span class="p">{</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">var</span> <span class="n">didCallExpensiveFunctionFlat</span> <span class="o">=</span> <span class="nb">false</span>
</span><span class='line'>
</span><span class='line'>    <span class="kr">override</span> <span class="k">func</span> <span class="n">someExpensiveMethodThatReturnsAStringFromTheWeb</span><span class="p">()</span> <span class="o">-&gt;</span> <span class="n">String</span> <span class="p">{</span>
</span><span class='line'>        <span class="n">didCallExpensiveFunctionFlag</span> <span class="o">=</span> <span class="nb">true</span>
</span><span class='line'>        <span class="k">return</span> <span class="s">&quot;Finally! Some content!&quot;</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now we can test all this in our test case:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class='swift'><span class='line'><span class="k">func</span> <span class="nf">testThatTheExpensiveFunctionGetsCalled</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">let</span> <span class="n">fakeSooperClass</span> <span class="o">=</span> <span class="n">FakeSooperClass</span><span class="p">()</span>
</span><span class='line'>
</span><span class='line'>    <span class="c1">// Code that eventually ends up with someExpensiveFunctionThatReturnsAStringFromTheWeb() being called,</span>
</span><span class='line'>    <span class="c1">// like this:</span>
</span><span class='line'>    <span class="c1">// let result = fakeSooperClass.someExpensiveFunctionThatReturnsAStringFromTheWeb()</span>
</span><span class='line'>
</span><span class='line'>    <span class="c1">// Set an assertion to check that the flag</span>
</span><span class='line'>    <span class="n">XCTAssert</span><span class="p">(</span><span class="n">fakeSooperClass</span><span class="p">.</span><span class="n">didCallExpensiveFunction</span> <span class="o">==</span> <span class="nb">true</span><span class="p">,</span> <span class="s">&quot;expected function to be called, but wasn&#39;t&quot;</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>If the function WAS called, the flag will be flipped, and the assertion will pass. If for some reason the function didn&rsquo;t get called, then the flag will be <code>false</code> and will cause the assertion to fail.</p>

<p>You could also extend this to keep track of the number of times the function gets called, by incrementing a counter. It uses exactly the same approach of overriding a function in a fake class, and checking the results with an assertion.</p>

<p>So, not difficult to do. Not only that, but rolling your own mocks and expectations in Swift also has the benefit that you&rsquo;re not dependent on external 3rd party libraries with all the attendent complexities that these can sometimes bring along.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Testing NSUserDefaults]]></title>
    <link href="http://adoptioncurve.net/archives/2015/03/testing-nsuserdefaults"/>
    <updated>2015-03-08T13:06:44+00:00</updated>
    <id>http://adoptioncurve.net/archives/2015/03/testing-nsuserdefaults</id>
    <content type="html"><![CDATA[<p><code>NSUserDefaults</code> is where you can store persistent app settings, as an alternative to storing them in some kind of in-app database. You shouldn&rsquo;t try to store actual application data in <code>NSUserDefaults</code>, but they are useful for capturing &ldquo;small&rdquo; settings like environment URLs and so on.</p>

<p>If you&rsquo;re using <code>NSUserDefaults</code>, you should be testing <code>NSUserDefaults</code>. Here&rsquo;s how.</p>

<p>One of the most common testing scenarios is that you want to store some value in the defaults store so that it can be read out later.  This is the process for testing that your code actually does so.  Assume that we&rsquo;ve got a class called <code>myClass</code> which has an <code>IBAction</code> method called <code>didTapUpdateSettingsButton</code> which will write out a specific value.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
</pre></td><td class='code'><pre><code class='objc'><span class='line'><span class="n">it</span><span class="p">(</span><span class="s">@&quot;should write the configured environment to the user defaults&quot;</span><span class="p">),</span> <span class="o">^</span><span class="p">{</span>
</span><span class='line'>
</span><span class='line'>  <span class="bp">NSString</span> <span class="o">*</span><span class="n">apiUrl</span> <span class="o">=</span> <span class="s">@&quot;http://foo.com/bar&quot;</span><span class="p">;</span>
</span><span class='line'>  <span class="bp">NSString</span> <span class="o">*</span><span class="n">theKey</span> <span class="o">=</span> <span class="s">@&quot;defaultApiUrl&quot;</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>  <span class="kt">id</span> <span class="n">mockStandardDefaults</span> <span class="o">=</span> <span class="p">[</span><span class="bp">NSUserDefaults</span> <span class="n">nullMock</span><span class="p">];</span>
</span><span class='line'>  
</span><span class='line'>  <span class="p">[</span><span class="bp">NSUserDefaults</span> <span class="nl">stub</span><span class="p">:</span><span class="k">@selector</span><span class="p">(</span><span class="n">standardUserDefaults</span><span class="p">)</span> <span class="nl">andReturn</span><span class="p">:</span><span class="n">mockStandardDefaults</span><span class="p">];</span>
</span><span class='line'>  
</span><span class='line'>  <span class="p">[[</span><span class="n">mockStandardDefaults</span> <span class="n">should</span><span class="p">]</span> <span class="nl">receive</span><span class="p">:</span><span class="k">@selector</span><span class="p">(</span><span class="nl">setObject</span><span class="p">:</span><span class="nl">forKey</span><span class="p">:)</span> <span class="nl">withArguments</span><span class="p">:</span><span class="n">theObject</span><span class="p">,</span> <span class="n">theKey</span><span class="p">];</span>
</span><span class='line'>  
</span><span class='line'>  <span class="p">[[</span><span class="n">mockStandardDefaults</span> <span class="n">should</span><span class="p">]</span> <span class="nl">receive</span><span class="p">:</span><span class="k">@selector</span><span class="p">(</span><span class="n">sychronize</span><span class="p">)];</span>
</span><span class='line'>  
</span><span class='line'>  <span class="p">[</span><span class="n">myClass</span> <span class="nl">didTapUpdateSettingsButton</span><span class="p">:</span><span class="nb">nil</span><span class="p">];</span>
</span><span class='line'>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Walking through this, we first create variables for the key and object that we are expecting the <code>didTapUpdateSettings</code> method to attempt to write to the defaults store.</p>

<p>Next, we create a mock object which will stand in for the instance of the <code>NSUserDefaults</code> class that would normally be returned by the <code>[NSUserDefaults standardUserDefaults]</code> method. We&rsquo;re going to use this mock to catch and test the messages that our code under test sends. It&rsquo;s created as a null mock here so that it won&rsquo;t complain if it gets messages other than the ones that we send it.</p>

<p>Then we need to stub the <code>standardUserDefaults</code> method of the real, live <code>NSUserDefaults</code> class, and return our mock instance instead of the real thing.</p>

<p>Once we&rsquo;ve stubbed out <code>NSUserDefaults</code>, we can now set some expectations about what our mock <code>standardUserDefaults</code> will receive. There are two things we&rsquo;re interested in - firstly, that it receives the <code>setObject:forKey</code> message with the values that we expect. If that message isn&rsquo;t received, or the values differ from what we expect, then there&rsquo;s something wrong with the code that we&rsquo;re writing.</p>

<p>Secondly, we&rsquo;re also setting an expectation that the mock receives the <code>synchronize</code> message. This saves the values that we&rsquo;ve updated - not sending a <code>synchronize</code> message to <code>NSUserDefaults</code> is a common mistake, and hard to diagnost - with a specific test, we&rsquo;ll catch any situations where we forget that final step.</p>

<p>Finally, we invoke the code under test by &ldquo;tapping&rdquo; the button (or in this case, calling the <code>IBAction</code> method that the button is wired up to).</p>

<p>If you&rsquo;re taking a test-first approach to writing the code, obviously this will initially fail.  But by fixing each failing assertion in turn, you&rsquo;ll end up with a method that both writes and saves the correct values.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Where Has the iOS8 Simulator Gone?!?]]></title>
    <link href="http://adoptioncurve.net/archives/2014/12/where-has-the-ios8-simulator-gone"/>
    <updated>2014-12-04T13:40:15+00:00</updated>
    <id>http://adoptioncurve.net/archives/2014/12/where-has-the-ios8-simulator-gone</id>
    <content type="html"><![CDATA[<p>With Xcode 6 and the new iOS8 Simulators, Apple thought it would be a good idea to move the location of the Simulator files. That&rsquo;s not usually a problem, because there&rsquo;s only a few specific circumstances when you need to access the files underlying the Simulator&rsquo;s functions.</p>

<p>If you <em>do</em> need to access those files, the chances are that you can&rsquo;t find them anymore.</p>

<p>Instead of looking in</p>

<p><code>~/Library/Application Support/iPhone Simulator/</code></p>

<p>you&rsquo;ll find them instead in</p>

<p><code>~/Library/Developer/CoreSimulator/Devices/*</code></p>

<p>Which at least is easier to embed into scripts thanks to the lack of spaces in the path.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Working With Size Classes in Interface Builder]]></title>
    <link href="http://adoptioncurve.net/archives/2014/08/working-with-size-classes-in-interface-builder"/>
    <updated>2014-08-16T11:30:24+01:00</updated>
    <id>http://adoptioncurve.net/archives/2014/08/working-with-size-classes-in-interface-builder</id>
    <content type="html"><![CDATA[<p>Android used to be notorious amongst iOS developers for its practically infinite permutations of interface size. Viewed from the iOS world, this used to look like a problem, because iOS didn&rsquo;t really provide much in the way of support for building interfaces of different sizes.</p>

<p>If you were building a universal app that supported both iPhone and iPad, there was a tendency to end up with a lot of <code>if deviceType == kIpad</code>-style code.</p>

<p>AutoLayout was the first part of fixing that problem, and the job&rsquo;s been completed with iOS 8 and size classes.  This is probably the least-sexy feature introduced in 8, but it&rsquo;s definitely one of the more important.</p>

<h3>Some quick background on size classes</h3>

<p>There are currently two size classes - <code>horizontal</code> and <code>vertical</code>, and each one comes in two sizes - <code>regular</code> and <code>compact</code>. The current orientation of the device can be described as a combination of the sizes:</p>

<ul>
<li><code>Horizontal regular, vertical regular</code>: iPad in either orientation</li>
<li><code>Horizontal compact, vertical regular</code>: iPhone portrait</li>
<li><code>Horizontal regular, vertical compact</code>: no current device</li>
<li><code>Horizontal compact, vertical compact</code>: iPhone landscape</li>
</ul>


<p><img src="http://adoptioncurve.net/images/2014/08/sizeClasses.png" width="400"></p>

<p>Storyboards and nib files now support these size classes - so you can think of them as having up to four different layouts contained within the same file. At the bottom of the Interface Builder window, there&rsquo;s now a control that allows you to switch between each combination:</p>

<p><img src="http://adoptioncurve.net/images/2014/08/ibCombination.png" width="300"></p>

<p>Every control or AutoLayout constraint can exist in one, several or all of the size classes. This means that you can build interfaces that change depending on device type and/or orientation <em>without any code</em>. Controls can appear or disappear, change size, or change arrangements - all based on the layout that you create in Interface Builder.</p>

<!-- more -->


<h3>Checking size classes</h3>

<p>To demonstrate how the size classes change as the device rotates, you can use the a new callback method that&rsquo;s called as the interface changes:</p>

<pre><code>-(void)willTransitionToTraitCollection:(UITraitCollection *)newCollection
             withTransitionCoordinator:(id&lt;UIViewControllerTransitionCoordinator&gt;)coordinator {
    NSLog(@"Trait collection = %@", newCollection);
}
</code></pre>

<p>This will display the trait collection that each orientation triggers:</p>

<pre><code>2014-08-16 19:04:49.785 Adaptr[6522:213857] Trait collection = &lt;UITraitCollection: 0x7fa983c13a10; _UITraitNameUserInterfaceIdiom = Phone, _UITraitNameDisplayScale = 2.000000, _UITraitNameHorizontalSizeClass = Compact, _UITraitNameVerticalSizeClass = Regular, _UITraitNameTouchLevel = 0, _UITraitNameInteractionModel = 1&gt;
</code></pre>

<h3>How to build adaptive layouts</h3>

<p>To demonstrate this, this is a simple universal app that changes layout depending on device and orientation.  You can <a href="https://github.com/timd/Adaptr">download the full project from here</a>, or follow along.  I&rsquo;m assuming that you&rsquo;re using Xcode 6 Beta 5 at a minimum.</p>

<p>To start with, create a new universal Single View application. This will create an App Delegate, a view controller and a storyboard. I&rsquo;m going to ignore the code entirely, and focus on the Storyboard alone (if you&rsquo;re working with xib files, the process is exactly the same).</p>

<p>Before getting going, it&rsquo;s worth doing a bit of tweaking to Xcode so that you can see what&rsquo;s going on. If the Assistant Editor isn&rsquo;t visible, open it on the right (<code>View</code> -> <code>Assistant Editor</code> -> <code>Assistant Editors on Right</code>) and then switch the Assistant Editor to <code>Preview</code> mode:</p>

<p><img src="http://adoptioncurve.net/images/2014/08/previewMode.png" width="400"></p>

<p>This will show a preview of the storyboard in the right hand pane - by default, it&rsquo;s set up for a 4" iPhone. You can add other devices by clicking on the <code>+</code> icon at the bottom of the preview and selecting the device(s) that you need. They appear side-by-side in the preview pane, so if you haven&rsquo;t invested in a Thunderbolt Display so far, now would be a good time to do so.</p>

<h3>The basic layout</h3>

<p>By default, Interface Builder creates a Storyboard with a square &lsquo;Any, Any&rsquo; layout - in other words, anything you do with this layout will be common across all devices.</p>

<p>We&rsquo;re going to start by centering a red block with a constant border. Drag a <code>UIView</code> object into the main view, set the size to 200 x 200, center it in the superview and set the background colour to red.  In the Storyboard, it will look like this:</p>

<p><img src="http://adoptioncurve.net/images/2014/08/storyboard.png" width="400"></p>

<p>However, if you look at the preview (or run the app in the Simulator) for each device, you&rsquo;ll see that things look very different:</p>

<p><img src="http://adoptioncurve.net/images/2014/08/previewOne.png" width="400"></p>

<p>To fix this, we need to add some AutoLayout constraints.  Add constraints to pin the leading, trailing, top and bottom spaces to 50 points:</p>

<p><img src="http://adoptioncurve.net/images/2014/08/constraints.png" width="400"></p>

<p>Run the app again, and this time the red block will be placed correctly regardless of which device you use (you can also change the size of the device in the Resizable Simulator, and the layout will still work.)</p>

<p><img src="http://adoptioncurve.net/images/2014/08/simulatorOne.png"></p>

<h3>Altering constraints in different layouts</h3>

<p>So far, we haven&rsquo;t done anything that previous versions of iOS and Xcode could do. To demonstrate how the layout can change between devices, we&rsquo;ll alter things so that in landscape, the red block fills the entire screen.</p>

<p>To do this we need to change the layout classes that the constraints are added to. If you select a constraint in the object tree then view the Attributes inspector, you&rsquo;ll see an <code>Installed</code> checkbox, with a small <code>+</code> to the left:</p>

<p><img src="http://adoptioncurve.net/images/2014/08/attributesOne.png" width="400"></p>

<p>By default this constraint is installed in <em>all</em> layout classes - what we need to do is to add the appropriate layout classes so that the constraints can be added to the appropriate one.  Click the <code>+</code> button, then add a compact width, regular height layout:</p>

<p><img src="http://adoptioncurve.net/images/2014/08/sizeClassOne.png" width="400"></p>

<p>When you add the new layout, the constraint will be automatically added to both layouts - deselect the <code>Installed</code> checkbox to remove it from the default layout:</p>

<p><img src="http://adoptioncurve.net/images/2014/08/sizeClassTwo.png" width="300"></p>

<p>Repeat the same process for the other three constraints. As you remove the constraints from the default layout, you&rsquo;ll see them disappear from the main Interface Builder pane, and become greyed out in the view tree:</p>

<p><img src="http://adoptioncurve.net/images/2014/08/removedConstraints.png"></p>

<p>To see the size class where the constraints <em>are</em> active, change it using the selectors at the bottom of the Interface Builder pane:</p>

<p><img src="http://adoptioncurve.net/images/2014/08/changeConstraints.png" width="300"></p>

<p>Once you&rsquo;ve switched layout, you&rsquo;ll see them reappear:</p>

<p><img src="http://adoptioncurve.net/images/2014/08/reappearingConstraints.png"></p>

<p>If you run the app again in the iPhone Simulator everything will look fine in portrait orientation. Rotate into landscape, though, and things go horribly wrong - the red block disappears, albeit with a nice animation. This is because there are no layout contraints present in this layout class combination, so AutoLayout does its best to figure out what should happen and gets it wrong. To fix this, we need to add constraints for the landscape scenario.</p>

<p>In Interface Builder, switch the layout class to Any width, Compact height:</p>

<p><img src="http://adoptioncurve.net/images/2014/08/anyCompact.png"></p>

<p>Now add four new AutoLayout contraints - leading, trailing, top and bottom spaces - and set the constant value for each one to 0. Note that each constraint is added to the Any, Compact layout and <em>not</em> the default:</p>

<p><img src="http://adoptioncurve.net/images/2014/08/redBlockTop.png" width="400"></p>

<p>Run the app again, and as you rotate the Simulator into landscape the red block will be animated to fill the screen:</p>

<p><img src="http://adoptioncurve.net/images/2014/08/fullRedBlock.png"></p>

<h3>Adding and removing views in different layouts</h3>

<p>As well as adding. removing and changing contraints between different layouts, you can do the same thing with views and controls. This could allow you to build completely different interfaces in portrait and landscape orientations; or as an alternative to separate interfaces for different classes of device.</p>

<p>To illustrate this, we&rsquo;ll update the current interface to add a white block that appears in landscape:</p>

<p><img src="http://adoptioncurve.net/images/2014/08/landscapeWhite.png"></p>

<p>Start by switching to Any width, Any height and adding a <code>UIView</code> to the interface. Make sure it&rsquo;s a sibling view of the red block, and set its background colour to white.</p>

<p>Next, change to Any width, Compact height and add constraints to set a 50 point inset on all four edges.</p>

<p>If you run the Simulator now, you&rsquo;ll see that the white block is the correct size and position in landscape, but the transition between landscape and portrait could be better:</p>

<p><img src="http://adoptioncurve.net/images/2014/08/inProgress.gif"></p>

<p>This is because the view animates between the constraints in each size class combination, and at the moment those in portrait are undefined.</p>

<p>To fix this, switch to Compact width, Regular height and add constraints to centre the white block and fix its height and width to zero. You&rsquo;ll also need to reduce the height and width constraint priorities to 750 to prevent a clash between size and inset constraints.</p>

<p><img src="http://adoptioncurve.net/images/2014/08/finalConstraints.png" width="400"></p>

<p>This fixes the start point of the portrait-to-landscape animation, and the end point of the landscape-to-portrait. Because the start and end points are defined, the transition of the white block is smoothly animated:</p>

<p><img src="http://adoptioncurve.net/images/2014/08/final.gif"></p>

<h3>Where to go from here</h3>

<p>By using size classes and constraints, it&rsquo;s going to be possible to build up responsive interfaces in a way that wasn&rsquo;t feasible before iOS8. As well as simplifying the management of device rotation, you can also create universal interfaces - something that should make targeting multiple device types a lot easier.</p>

<p>The other interesting extrapolation here is that we&rsquo;ve now got all the tools we need to build interfaces for <em>any</em> size of device - whether it&rsquo;s an iPhone 6 with a large screen; or apps for Apple TV; or even CarPlay. Maybe the long-awaited Apple TV SDK might be on the way&hellip;?</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Many Forms of Swift Functions]]></title>
    <link href="http://adoptioncurve.net/archives/2014/08/the-many-forms-of-swift-functions-a-cheatsheet"/>
    <updated>2014-08-02T15:19:38+01:00</updated>
    <id>http://adoptioncurve.net/archives/2014/08/the-many-forms-of-swift-functions-a-cheatsheet</id>
    <content type="html"><![CDATA[<p>There are a somewhat bewildering variety of forms that a Swift function can take, depending on the permutations of parameters and return values that you want to use. Here&rsquo;s a cheat summary:</p>

<div><script src='https://gist.github.com/efb965552945366ae14a.js'></script>
<noscript><pre><code>THE MANY FORMS OF SWIFT FUNCTIONS – A CHEATSHEET
================================================

No parameters, no return value

    func foo()

    called with

    foo()

No parameters, return type

    func foo() -&gt; Int

    called with

    var a = foo()

Single parameter, no return value

    func foo(bar: Int)

    called with

    foo(10)

Single parameter, return value

    func foo(bar: Int) -&gt; Int

    called with

    var a = foo(10)

Multiple parameters, return value

    func foo(bar: int, bash: String) -&gt; Int

    called with

    var a = foo(10, &quot;hello&quot;)

One or more parameters, multiple return values

    func foo(bar: Int) -&gt; (bash: Int, baz: String)

    called with

    var a = foo(10, &quot;Hello&quot;)

    a.bash = ...
    a.baz = &quot;...&quot;

One or more parameters, optional multiple return values

    func foo(bar: Int) -&gt; (bash: Int, baz: String)?

    called with

    if let a = foo(10) {
        println (&quot;Bash is \(bash) and baz is \(baz)&quot;)
    }

Default parameters

    func foo(bar: Int, bash: String = &quot;bash!&quot;) -&gt; Int

    called with

    var a = foo(10)
    var b = foo(10, &quot;bling!&quot;)

External parameter names

    func foo(externalBar bar: Int) -&gt; Int

    called with

    var a = foo(externalBar: 10)
    
Opting out of external parameter names with default parameters

        func foo(_ bar: Int, _ bash: String = &quot;bash!&quot;) -&gt; Int

        called with

        var a = foo(10)
        var b = foo(10, &quot;Bling!&quot;)

Shorthand external parameter names

    func foo(#bar: Int, #bash: String) -&gt; Int

    called with

    var a = foo(bar: 10, bash: &quot;Bling!&quot;)

External parameter names with default parameters

    func foo(#bar: Int, bash: String = &quot;bash!&quot;) -&gt; Int

    called with

    var a = foo(bar: 10)
    var b = foo(bar: 10, bash: &quot;Bling!&quot;)

Variadic parameters

    func foo(bar: Int, bash: String...) -&gt; Int

    called with

    var a = foo(10, &quot;Bling!&quot;, &quot;Clang!&quot;)

Variable parameters

    func foo(var bar: Int, var bash: String) -&gt; Int

    called with

    var a = foo(10, &quot;Bling!&quot;)

In-out parameters

    func foo(inout bar: Int, inout bash: String)

    called with

    var x = 10
    var y = &quot;Bling!&quot;
    foo(&amp;x, &amp;y)

</code></pre></noscript></div>


<p><a href="http://adoptioncurve.net/assets/docs/SwiftFunctionFormsCheatsheet.pdf">Here&rsquo;s a downloadable PDF version.</a></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[A Minimum Viable tableView in Swift]]></title>
    <link href="http://adoptioncurve.net/archives/2014/07/a-minimum-viable-tableview-in-swift"/>
    <updated>2014-07-20T11:33:34+01:00</updated>
    <id>http://adoptioncurve.net/archives/2014/07/a-minimum-viable-tableview-in-swift</id>
    <content type="html"><![CDATA[<p><a href="https://github.com/timd/SwiftTable">This GitHub repo</a> is a minimum viable implementation of a <code>UITableView</code> in Swift.  Here&rsquo;s a swift (badum, tish) tutorial on creating a <code>UITableView</code> using the new language.</p>

<p><em>This code has been updated for Swift 1.0 and Xcode 6.0.1</em></p>

<p>The project consists consists of a single storyboard with a table view control, and a view controller written in Swift:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
<span class='line-number'>37</span>
<span class='line-number'>38</span>
<span class='line-number'>39</span>
<span class='line-number'>40</span>
<span class='line-number'>41</span>
<span class='line-number'>42</span>
<span class='line-number'>43</span>
<span class='line-number'>44</span>
<span class='line-number'>45</span>
<span class='line-number'>46</span>
<span class='line-number'>47</span>
<span class='line-number'>48</span>
<span class='line-number'>49</span>
<span class='line-number'>50</span>
<span class='line-number'>51</span>
<span class='line-number'>52</span>
<span class='line-number'>53</span>
<span class='line-number'>54</span>
<span class='line-number'>55</span>
<span class='line-number'>56</span>
<span class='line-number'>57</span>
<span class='line-number'>58</span>
<span class='line-number'>59</span>
<span class='line-number'>60</span>
<span class='line-number'>61</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
</span><span class='line'>    
</span><span class='line'>    let cellIdentifier = "cellIdentifier"
</span><span class='line'>    var tableData = [String]()
</span><span class='line'>    
</span><span class='line'>    @IBOutlet var tableView: UITableView?
</span><span class='line'>    
</span><span class='line'>    override func viewDidLoad() {
</span><span class='line'>        super.viewDidLoad()
</span><span class='line'>
</span><span class='line'>        // Register the UITableViewCell class with the tableView
</span><span class='line'>        
</span><span class='line'>        
</span><span class='line'>        self.tableView?.registerClass(UITableViewCell.self, forCellReuseIdentifier: self.cellIdentifier)
</span><span class='line'>        
</span><span class='line'>        // Setup table data
</span><span class='line'>        for index in 0...100 {
</span><span class='line'>            self.tableData.append("Item \(index)")
</span><span class='line'>        }
</span><span class='line'>    }
</span><span class='line'>
</span><span class='line'>    override func didReceiveMemoryWarning() {
</span><span class='line'>        super.didReceiveMemoryWarning()
</span><span class='line'>        // Dispose of any resources that can be recreated.
</span><span class='line'>    }
</span><span class='line'>
</span><span class='line'>    // UITableViewDataSource methods
</span><span class='line'>    
</span><span class='line'>    func numberOfSectionsInTableView(tableView: UITableView) -&gt; Int {
</span><span class='line'>        return 1
</span><span class='line'>    }
</span><span class='line'>    
</span><span class='line'>    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {
</span><span class='line'>        return tableData.count
</span><span class='line'>    }
</span><span class='line'>    
</span><span class='line'>    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell {
</span><span class='line'>        var cell = tableView.dequeueReusableCellWithIdentifier(self.cellIdentifier) as UITableViewCell
</span><span class='line'>        
</span><span class='line'>        cell.textLabel?.text = self.tableData[indexPath.row]
</span><span class='line'>        
</span><span class='line'>        return cell
</span><span class='line'>    }
</span><span class='line'>    
</span><span class='line'>    // UITableViewDelegate methods
</span><span class='line'>    
</span><span class='line'>    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
</span><span class='line'>
</span><span class='line'>        let alert = UIAlertController(title: "Item selected", message: "You selected item \(indexPath.row)", preferredStyle: UIAlertControllerStyle.Alert)
</span><span class='line'>    
</span><span class='line'>        alert.addAction(UIAlertAction(title: "OK",
</span><span class='line'>                                      style: UIAlertActionStyle.Default,
</span><span class='line'>                                    handler: {
</span><span class='line'>                                        (alert: UIAlertAction!) in println("An alert of type \(alert.style.hashValue) was tapped!")
</span><span class='line'>                                    }))
</span><span class='line'>        
</span><span class='line'>        self.presentViewController(alert, animated: true, completion: nil)
</span><span class='line'>        
</span><span class='line'>    }
</span><span class='line'>
</span><span class='line'>}</span></code></pre></td></tr></table></div></figure>




<!-- more -->


<h3>Housekeeping</h3>

<p>There are three upfront pieces of housekeeping that we need to do:</p>

<ul>
<li><p>create a <code>String</code> constant as a cell identifier (Swift is clever enough to infer the fact that it&rsquo;s a <code>String</code> when we define the constant):</p>

<p>  <code>let cellIdentifier = "cellIdentifier"</code></p></li>
<li><p>define an <code>Array</code> variable to contain the table&rsquo;s data. This is an <code>Array</code> of <code>Strings</code>, and we initialize this as empty as we declare it:</p>

<p>  <code>var tableData = [String]()</code></p></li>
<li><p>define a <code>UITableView</code> outlet to connect the table in the Storyboard:</p>

<p>  <code>@IBOutlet var tableView: UITableView?</code></p>

<p>  The outlet&rsquo;s defined as an optional, because it won&rsquo;t exist until the view has been instantiated (that&rsquo;s a similar approach to declaring outlets as <code>weak</code> with Objective-C).</p></li>
</ul>


<p>You&rsquo;ll also need to setup the Storyboard with a <code>UITableView</code> object that connects with the view controller as <code>dataSource</code> and <code>delegate</code>, and connects the view controller&rsquo;s <code>tableView</code> outlet with the table view.</p>

<h3>Registering a UITableViewCell class with the table</h3>

<p>So that the table can use <code>UITableViewCell</code> objects, we&rsquo;ll need to register the <code>UITableViewCell</code> class for use with the <code>cellIdentifier</code> that we created in the stage above.  The most logical place to do this is in the <code>viewDidLoad</code> method:</p>

<pre><code>self.tableView?.registerClass(UITableViewCell.self, forCellReuseIdentifier: self.cellIdentifier)
</code></pre>

<p>Swift&rsquo;s way of returning the class name for use with the <code>registerClass</code> method is subtly different from Objective-C - rather than using something along the lines of <code>[UICollectionViewCell class]</code>, in Swift you use <code>UICollectionViewCell.self</code>.</p>

<h3>Creating some table data</h3>

<p>Next, we need to create some data for the table to work with.  This is going to be held in the <code>tableData</code> array:</p>

<pre><code>for index in 0...100 {
    self.tableData.append("Item \(index)")
}
</code></pre>

<p>This uses Swift&rsquo;s <code>for-in</code> loop to create 100 <code>Strings</code> and append them to the <code>tableData</code> array.  The <code>\(...)</code> format is a <em>huge</em> improvement on the legacy <code>NSString stringWithFormat:</code> style&hellip;</p>

<h3>Telling the table about sections and rows</h3>

<p>The <code>UITableView</code> datasource methods haven&rsquo;t changed in iOS8 - you still need to inform the table how many sections and rows it will have.</p>

<p>(Technically, the table view will assume that it has one section unless you tell it otherwise, but I usually implement the <code>numberOfSectionsInTableview</code> method out of sheer habit):</p>

<pre><code>func numberOfSectionsInTableView(tableView: UITableView) -&gt; Int {
    return 1
}
</code></pre>

<p>There&rsquo;s no practical difference between the Swift and Objective-C versions, other than the syntactic differences - the method has am external parameter name of <code>tableView</code>, and returns an <code>Int</code>.</p>

<p>The same is also true of the <code>tableView:numberOfRowsInSection:</code> method:</p>

<pre><code>func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {
    return tableData.count
}
</code></pre>

<h3>Creating and returning cells</h3>

<p>Now that the table view knows how many sections and rows it has, the final step in a minimal implementation is to create and return cells on demand:</p>

<pre><code>func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath!) -&gt; UITableViewCell! {
    var cell = tableView.dequeueReusableCellWithIdentifier(self.cellIdentifier) as UITableViewCell
    cell.textLabel.text = self.tableData[indexPath.row]
    return cell
}
</code></pre>

<p>Once again, this is very straight-forward: we dequeue a cell with the appropriate identifier, configure its contents, and return it to the table view.  The <code>as</code> operator is <a href="https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/TypeCasting.html#//apple_ref/doc/uid/TP40014097-CH22-XID_445">force-downcasting</a> whatever is returned from the <code>tableView</code> into a <code>UITableViewCell</code>.</p>

<h3>Cell selection</h3>

<p>Although that&rsquo;s all that&rsquo;s needed to get the table view up and running, here&rsquo;s how a simple <code>UITableViewDelegate</code> method is implemented:</p>

<pre><code>func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    let alert = UIAlertController(title: "Item selected", message: "You selected item \(indexPath.row)", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil))
    self.presentViewController(alert, animated: true, completion: nil)
}
</code></pre>

<p>This method is fired when a cell is selected - no change there.  Here, we&rsquo;re creating an instance of <code>UIAlertController</code> which is the iOS8 replacement for the venerable <code>UIAlert</code> control:</p>

<pre><code>let alert = UIAlertController(title: "Item selected", message: "You selected item \(indexPath.row)", preferredStyle: UIAlertControllerStyle.Alert)
</code></pre>

<p>A vanilla <code>UIAlertController</code> doesn&rsquo;t have any user controls, so we need to add a <code>UIAlertAction</code> to it:</p>

<pre><code>alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil))
</code></pre>

<p>And then finally present the controller:</p>

<pre><code>self.presentViewController(alert, animated: true, completion: nil)
</code></pre>

<p>You&rsquo;ll notice that the last <code>handler</code> parameter of the <code>UIAlertAction</code> takes a block: this means that you can implement whatever actions you want to occur once the button has been tapped in-place, rather than having to link the alert controller to the view controller through a delegate.</p>

<p>That makes for much less code, and also keeps the action together with <code>UIAlertController</code> (helping to make the code more readable).</p>

<p>If you wanted to log something to the console, say, you could implement this:</p>

<pre><code>    alert.addAction(UIAlertAction(title: "OK",
                                  style: UIAlertActionStyle.Default,
                                handler: {
                                    (alert: UIAlertAction!) in println("An alert of type \(alert.style.hashValue) was tapped!")
                                }))
</code></pre>

<p>It&rsquo;s compact, certainly, but this is an example of something that does make me wonder why quite so many people rave about Swift as being more readable than Objective-C - I&rsquo;m really not sure this is actually <em>so</em> much of an improvement.</p>

<h3>Summary</h3>

<p>One of the killer features of Swift is the backwards-compatibility of it with the existing legacy of Objective-C and the iOS frameworks.  This is a good example of how the basic design patterns of the controls haven&rsquo;t changed at all - moving to Swift is just a case of getting to grips with the new syntax and language features.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Creating a Draggable UICollectionViewCell]]></title>
    <link href="http://adoptioncurve.net/archives/2014/07/creating-a-draggable-uicollectionviewcell"/>
    <updated>2014-07-16T16:56:00+01:00</updated>
    <id>http://adoptioncurve.net/archives/2014/07/creating-a-draggable-uicollectionviewcell</id>
    <content type="html"><![CDATA[<p>So here&rsquo;s the situation - you&rsquo;re creating an interactive <code>UICollectionView</code>, and you want to be able to drag a cell around the screen with a touch. To provide user feedback, you want the contents of the cell to follow the user&rsquo;s finger as it moves around.</p>

<p>The problem is that unless you&rsquo;re using a completely custom collection view layout, you can&rsquo;t move the cell itself. The collection view is in charge of where things are displayed, and it&rsquo;s a major pain to override this - especially if you&rsquo;re using a flow layout.  Reimplementing <code>UICollectionViewFlowLayout</code> from scratch is a decidedly non-trivial undertaking.</p>

<p>The answer lies in a hack. Create a <em>copy</em> of the contents of the cell as an image, then drag <em>this</em> around the screen underneath your finger. Much easier.</p>

<p>Here&rsquo;s an example - it assumes that you&rsquo;ve previously created and attached a <code>UIPanGestureRecognizer</code> to the collection view, and tied this to a method called <code>handlePan:</code> in your view controller.  There&rsquo;s also a <code>UIImageView</code> property on the view controller called <code>movingCell</code>.</p>

<figure class='code'><figcaption><span>A draggable UICollectionViewCell</span><a href='https://gist.github.com/31e2e5bd75e99405bc35.git'>link</a></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
</pre></td><td class='code'><pre><code class='objc'><span class='line'><span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="nl">handlePan</span><span class="p">:(</span><span class="bp">UIPanGestureRecognizer</span> <span class="o">*</span><span class="p">)</span><span class="n">panRecognizer</span> <span class="p">{</span>
</span><span class='line'>
</span><span class='line'>    <span class="bp">CGPoint</span> <span class="n">locationPoint</span> <span class="o">=</span> <span class="p">[</span><span class="n">panRecognizer</span> <span class="nl">locationInView</span><span class="p">:</span><span class="nb">self</span><span class="p">.</span><span class="n">collectionView</span><span class="p">];</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">if</span> <span class="p">(</span><span class="n">panRecognizer</span><span class="p">.</span><span class="n">state</span> <span class="o">==</span> <span class="n">UIGestureRecognizerStateBegan</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>
</span><span class='line'>        <span class="bp">NSIndexPath</span> <span class="n">indexPathOfMovingCell</span> <span class="o">=</span> <span class="p">[</span><span class="nb">self</span><span class="p">.</span><span class="n">collectionView</span> <span class="nl">indexPathForItemAtPoint</span><span class="p">:</span><span class="n">locationPoint</span><span class="p">];</span>
</span><span class='line'>        <span class="bp">UICollectionViewCell</span> <span class="o">*</span><span class="n">cell</span> <span class="o">=</span> <span class="p">[</span><span class="nb">self</span><span class="p">.</span><span class="n">collectionView</span> <span class="nl">cellForItemAtIndexPath</span><span class="p">:</span><span class="n">indexPathOfMovingCell</span><span class="p">];</span>
</span><span class='line'>
</span><span class='line'>        <span class="n">UIGraphicsBeginImageContext</span><span class="p">(</span><span class="n">cell</span><span class="p">.</span><span class="n">bounds</span><span class="p">.</span><span class="n">size</span><span class="p">);</span>
</span><span class='line'>        <span class="p">[</span><span class="n">cell</span><span class="p">.</span><span class="n">layer</span> <span class="nl">renderInContext</span><span class="p">:</span><span class="n">UIGraphicsGetCurrentContext</span><span class="p">()];</span>
</span><span class='line'>        <span class="bp">UIImage</span> <span class="o">*</span><span class="n">cellImage</span> <span class="o">=</span> <span class="n">UIGraphicsGetImageFromCurrentImageContext</span><span class="p">();</span>
</span><span class='line'>        <span class="n">UIGraphicsEndImageContext</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'>        <span class="nb">self</span><span class="p">.</span><span class="n">movingCell</span> <span class="o">=</span> <span class="p">[[</span><span class="bp">UIImageView</span> <span class="n">alloc</span><span class="p">]</span> <span class="nl">initWithImage</span><span class="p">:</span><span class="n">cellImage</span><span class="p">];</span>
</span><span class='line'>        <span class="p">[</span><span class="nb">self</span><span class="p">.</span><span class="n">movingCell</span> <span class="nl">setCenter</span><span class="p">:</span><span class="n">locationPoint</span><span class="p">];</span>
</span><span class='line'>        <span class="p">[</span><span class="nb">self</span><span class="p">.</span><span class="n">movingCell</span> <span class="nl">setAlpha</span><span class="p">:</span><span class="mf">0.75f</span><span class="p">];</span>
</span><span class='line'>        <span class="p">[</span><span class="nb">self</span><span class="p">.</span><span class="n">collectionView</span> <span class="nl">addSubview</span><span class="p">:</span><span class="nb">self</span><span class="p">.</span><span class="n">movingCell</span><span class="p">];</span>
</span><span class='line'>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">if</span> <span class="p">(</span><span class="n">panRecognizer</span><span class="p">.</span><span class="n">state</span> <span class="o">==</span> <span class="n">UIGestureRecognizerStateChanged</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="p">[</span><span class="nb">self</span><span class="p">.</span><span class="n">movingCell</span> <span class="nl">setCenter</span><span class="p">:</span><span class="n">locationPoint</span><span class="p">];</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">if</span> <span class="p">(</span><span class="n">panRecognizer</span><span class="p">.</span><span class="n">state</span> <span class="o">==</span> <span class="n">UIGestureRecognizerStateEnded</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="p">[</span><span class="nb">self</span><span class="p">.</span><span class="n">movingCell</span> <span class="n">removeFromSuperview</span><span class="p">];</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>When the pan gesture recognizer fires, it calls the <code>handlePan:</code> method with itself as a parameter.</p>

<p>A <code>UIPanGestureRecognizer</code> has three states that we&rsquo;re interested in - <code>UIGestureRecognizerStateBegan</code> (which is fired as the first touch starts), <code>UIGestureRecognizerStateChanged</code>(which fires as the touch moves) and <code>UIGestureRecognizerStateEnded</code> (which fires as the finger is lifted).</p>

<p>We hook into the <code>UIGestureRecognizerStateBegan</code> event, and get the location where the pan gesture is occurring:</p>

<pre><code>CGPoint locationPoint = [panRecognizer locationInView:self.collectionView];
</code></pre>

<p>Then if the touches have just begun, we grab the cell in which the touch started:</p>

<pre><code>NSIndexPath *indexPathOfMovingCell = [self.collectionView indexPathForItemAtPoint:locationPoint];

UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPathOfMovingCell];
</code></pre>

<p>and create a UIImage out of the cell&rsquo;s <code>layer</code>:</p>

<pre><code>UIGraphicsBeginImageContext(cell.bounds.size);

[cell.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage *cellImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();
</code></pre>

<p>Finally, we use this <code>UIImage</code> to populate a <code>UIImageView</code> property, and update the center of the <code>UIImageView</code> so that it lies underneath the current location of the touch. I&rsquo;ve also tweaked the image&rsquo;s opacity to make it slightly translucent:</p>

<pre><code>self.movingCell = [[UIImageView alloc] initWithImage:cellImage];

[self.movingCell setCenter:locationPoint];

[self.movingCell setAlpha:0.75f];

[self.collectionView addSubview:self.movingCell];
</code></pre>

<p>Following the touches is just a case of updating the centre of the <code>UIImageView</code>:</p>

<pre><code>if (panRecognizer.state == UIGestureRecognizerStateChanged) {

    [self.movingCell setCenter:locationPoint];

}
</code></pre>

<p>And when the touches end, we remove the <code>UIImageView</code> from the <code>collectionView</code> completely:</p>

<pre><code>if (panRecognizer.state == UIGestureRecognizerStateEnded) {

    [self.movingCell removeFromSuperview];

}
</code></pre>

<p>This implementation simply removes the pseudo-cell from the screen when the touch finishes, but there&rsquo;s no reason why you can&rsquo;t do something like insert it back into the collection view at the point where it was &lsquo;dropped&rsquo;.  I&rsquo;ll put the code for this up in another post.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Mocking UICollectionViewLayouts]]></title>
    <link href="http://adoptioncurve.net/archives/2014/07/mocking-uicollectionviewlayouts"/>
    <updated>2014-07-10T15:01:00+01:00</updated>
    <id>http://adoptioncurve.net/archives/2014/07/mocking-uicollectionviewlayouts</id>
    <content type="html"><![CDATA[<p>At the heart of custom <code>UICollectionViewLayouts</code> are lots of calculations, and creating/debugging these by hand can be painful. It&rsquo;s easier in the long run to write tests to help with this - but setting up the stack of objects to make the tests run can be a bit involved.</p>

<p>Here&rsquo;s how I&rsquo;m doing it - using <code>XCTest</code> and <code>OCMock</code>, although there&rsquo;s no reason why this approach won&rsquo;t work with other test/mock frameworks like Kiwi etc.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
</pre></td><td class='code'><pre><code class='objc'><span class='line'><span class="p">-(</span><span class="kt">void</span><span class="p">)</span><span class="nf">testCalculateSpokeRadiusReturnsCorrectValueForTwoItems</span> <span class="p">{</span>
</span><span class='line'>
</span><span class='line'>    <span class="bp">UICollectionView</span> <span class="o">*</span><span class="n">collectionView</span> <span class="o">=</span> <span class="p">[[</span><span class="bp">UICollectionView</span> <span class="n">alloc</span><span class="p">]</span> <span class="nl">initWithFrame</span><span class="p">:</span><span class="n">CGRectMake</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">500</span><span class="p">,</span> <span class="mi">500</span><span class="p">)</span> <span class="nl">collectionViewLayout</span><span class="p">:</span><span class="nb">self</span><span class="p">.</span><span class="n">customLayout</span><span class="p">];</span>
</span><span class='line'>
</span><span class='line'>    <span class="kt">id</span> <span class="n">collectionViewMock</span> <span class="o">=</span> <span class="n">OCMPartialMock</span><span class="p">(</span><span class="n">collectionView</span><span class="p">);</span>
</span><span class='line'>    <span class="p">[[[</span><span class="n">collectionViewMock</span> <span class="n">stub</span><span class="p">]</span> <span class="nl">andReturnValue</span><span class="p">:</span><span class="l">@(</span><span class="mi">1</span><span class="l">)</span><span class="p">]</span> <span class="nl">numberOfItemsInSection</span><span class="p">:</span><span class="mi">0</span><span class="p">];</span>
</span><span class='line'>  
</span><span class='line'>    <span class="p">[</span><span class="n">collectionViewMock</span> <span class="nl">setCollectionViewLayout</span><span class="p">:</span><span class="nb">self</span><span class="p">.</span><span class="n">customLayout</span><span class="p">];</span>
</span><span class='line'>
</span><span class='line'>    <span class="p">[</span><span class="nb">self</span><span class="p">.</span><span class="n">customLayout</span> <span class="nl">setItemSize</span><span class="p">:</span><span class="n">CGSizeMake</span><span class="p">(</span><span class="mi">100</span><span class="p">,</span> <span class="mi">100</span><span class="p">)];</span>
</span><span class='line'>    <span class="p">[</span><span class="nb">self</span><span class="p">.</span><span class="n">customLayout</span> <span class="nl">setSidePadding</span><span class="p">:</span><span class="mf">10.0f</span><span class="p">];</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">XCTAssertEqual</span><span class="p">([</span><span class="nb">self</span><span class="p">.</span><span class="n">customLayout</span> <span class="n">calculateSpokeRadius</span><span class="p">],</span> <span class="mf">190.0f</span><span class="p">,</span> <span class="s">@&quot;should be 190.0f&quot;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>The process isn&rsquo;t too gnarly.  First, create a real, live <code>UICollectionView</code> instance and give it your custom layout (in this test, I&rsquo;d previously instantiated the custom layout object in the test setup):</p>

<pre><code>UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 500, 500) collectionViewLayout:self.customLayout];
</code></pre>

<p>Then create a partial mock:</p>

<pre><code>id collectionViewMock = OCMPartialMock(collectionView);
</code></pre>

<p>With this you, you can then stub out the <code>numberOfItemsInSection:</code> method and return the number of items you want to run the calculations for - by mocking out this method, you&rsquo;ve got no dependencies on your datasources.</p>

<p>The advantage of using a partial mock is that you only need to stub out the methods that you want to control - you can use everything else as you would with the real, live object.</p>

<pre><code>[[[collectionViewMock stub] andReturnValue:@(1)] numberOfItemsInSection:0];
</code></pre>

<p>Now link the custom layout and the collection view together:</p>

<pre><code>[collectionViewMock setCollectionViewLayout:self.customLayout];
</code></pre>

<p>A few custom layout settings (these will obviously depend on how you&rsquo;ve implemented your layout):</p>

<pre><code>[self.customLayout setItemSize:CGSizeMake(100, 100)];`
[self.customLayout setSidePadding:10.0f];`
</code></pre>

<p>Finally, after all this, you can actually fire the test:</p>

<pre><code>XCTAssertEqual([self.customLayout calculateSpokeRadius], 190.0f, @"should be 190.0f");
</code></pre>

<p>Here, I&rsquo;ve created a helper method inside the custom layout to calculate the radius from the centre of the collection view for various sizes of layout. That&rsquo;s often an easier approach to take - calculating layout attributes like item centre often involves some fiddly maths, so by breaking it up into chunks of helper methods you can test each bit piece-by-piece.</p>

<p>This tends to be easier in the long run than doing everything in one fell swoop, because you can spend a long time down the rabbit hole of figuring out where the layout is going wrong.  With this test, I can throw various sizes of collection view at the layout, and check that things will still work out OK.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Time for a Change]]></title>
    <link href="http://adoptioncurve.net/archives/2014/07/time-for-a-change"/>
    <updated>2014-07-08T15:35:00+01:00</updated>
    <id>http://adoptioncurve.net/archives/2014/07/time-for-a-change</id>
    <content type="html"><![CDATA[<p>A quick update, as it&rsquo;s easier to put it up here than condense down into 140 characters for a tweet. As of this week, I am no longer with Centralway - I remain under NDA, so that&rsquo;s all the details I can share.</p>

<p>This means I&rsquo;m available for hire. I do several things:</p>

<ul>
<li><p><em><strong>application architecture:</strong></em> figuring out how the user interactions, front-end, back-end and data pieces of a service need to work in order to play nicely together.</p></li>
<li><p><em><strong>project management:</strong></em> running Agile-style projects with mixed technical and non-technical teams.</p></li>
<li><p><em><strong>team management:</strong></em> building and running development teams, with all the challenges that are involved in a group of different skills and personalities.</p></li>
<li><p><em><strong>iOS development:</strong></em> hands-on code-cutting of apps.</p></li>
</ul>


<p>All of these I&rsquo;ve done in a variety of organisation shapes, sizes and cultures - so I&rsquo;ve got to be quite good at the spinning plates and herding cats that tend to be involved in getting a service up and running in today&rsquo;s online world. Ideally, I&rsquo;m looking for something that draws on all four of those areas.</p>

<p>Location-wise, I&rsquo;m interested in pretty-much anywhere in mainland Europe. Somewhere English/German-speaking would be a bonus.</p>

<p>Any leads will be gratefully received.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Why Swift Isn't Going to Change the App Industry Just Yet]]></title>
    <link href="http://adoptioncurve.net/archives/2014/06/why-swift-isnt-going-to-change-the-app-industry-just-yet"/>
    <updated>2014-06-08T12:53:00+01:00</updated>
    <id>http://adoptioncurve.net/archives/2014/06/why-swift-isnt-going-to-change-the-app-industry-just-yet</id>
    <content type="html"><![CDATA[<p>One of the common reactions to Monday&rsquo;s announcement of Apple&rsquo;s new <a href="https://developer.apple.com/swift/">Swift</a> language was that it&rsquo;s lowered the bar for iOS development. We can look now forward to the dawning of a halycon age where <a href="http://readwrite.com/2014/06/05/apple-swift-ios-app-development#awesm=~oGAUfKVkNPijyG">apps have never been easier and cheaper to create</a>.</p>

<p>The other way of looking at this idea is that as an established iOS developer, your industry might be about to get invaded by millions of newbies who haven&rsquo;t had to earn their stripes learning the intricacies of ObjectiveC. Your rates are about to go down, and the age of demand exceeding supply is over.</p>

<p>Both those are simplistic, and missing the bigger point. The bar to entry to this industry hasn&rsquo;t moved at all - if anything, <strong>it&rsquo;s been raised</strong>.</p>

<p>And that&rsquo;s because becoming a competent developer who can earn a professional living writing code isn&rsquo;t about mastering one area, it&rsquo;s about mastering FOUR.</p>

<p>It doesn&rsquo;t matter if you&rsquo;re writing mobile apps in a language that was announced 24 hours ago; or banking systems in a language that was designed by people who have since died of a ripe old age. If you don&rsquo;t understand these four areas, you&rsquo;ll suck as a developer.</p>

<p>You need to know the language, the paradigms, the frameworks and the environment of the platform that you&rsquo;re building for.</p>

<h3>Knowledge of the language</h3>

<p>In order to build any kind of software, you need a working knowledge of the language that you&rsquo;re using. To learn a language can be the work of a few hours; to master it can be the work of a lifetime.</p>

<p>Irrespective of where you lie along the continuum, there&rsquo;s a certain minimum amount of expertise that you will need to get by. You need a working knowledge of grammar in order to make yourself understood in speech, and coding is no different - understanding the syntax of a language is a prerequisite to being able to work with it.</p>

<h3>Knowledge of the paradigms</h3>

<p>When you think hard about what programming <em>actually is</em>, it gets philosophical in a way that you might not expect. You&rsquo;re in the business of taking tangible, real-world problems and reconstructing them in an intangible mental domain.</p>

<p>We talk about objects as if they&rsquo;re concrete physical entities - but building an app is actually a process of making a whole series of imaginary constructs, and then getting them to interact with each other.</p>

<p>To do that, you need a working knowledge of the underlying paradigms. This is taking the physical form of the language and making use of it. In order to use objects to break down a problem, you need to understand what they <em>are</em>.</p>

<p>Knowing only the details of a specific language isn&rsquo;t going to much use here - without the ability to comprehend the patterns of mental abstractions that you are expressing using the code of the language that you&rsquo;ve chosen.</p>

<h3>Knowledge of the frameworks</h3>

<p>Knowing what an object is, and how you create one with Swift or Objective-C or whatever language you&rsquo;re working with, still isn&rsquo;t enough. Next, you need a knowledge of the frameworks.</p>

<p>While it <em>might</em> be possible to build every aspect of an iOS app from scratch, that&rsquo;s not a practical way to work. So instead we rely on the frameworks that Apple provides. Table views are a standard control - but they behave in a particular way, and you need an understanding of how they fit together and operate in order to exploit them.</p>

<p>There are so many frameworks involved in iOS that it&rsquo;s probably not a practical proposition to even attempt to understand all of them.</p>

<p>But some are unavoidable - you&rsquo;re not going to get far without knowing even the basics of UIKit, for example.</p>

<p> To understand this takes not just a knowledge of the language that they&rsquo;re built in, but also the underlying paradigms that they&rsquo;re exploiting. Knowing how to set a table view&rsquo;s delegate is one thing, but you also need to know what a delegate actually <em>is</em>.</p>

<h3>Knowledge of the environment</h3>

<p>Assuming a working ability with the language, the paradigms and the frameworks, you&rsquo;re now in a position to start building things. But only knowing those three is missing one vital part - and that&rsquo;s the understanding of the environment in which you&rsquo;re operating.</p>

<p>The shorthand way of referring to this is user experience - why your interface is laid out the way it is, and the workflows that your app provides in order to solve the particular problem it is dealing with.</p>

<p>But this is a complex mix of physical contraints and psychology. Force your users to rely on voice input in a noisy environment - or large amounts of text input on a tiny keyboard - and they&rsquo;ll struggle to interact with your app. Forcing them to <em>think</em> about how they need to interact, and they&rsquo;re likely to give up and find an easier alternative.</p>

<h3>Where does this leave Swift?</h3>

<p>Swift doesn&rsquo;t change the fundementals of what it takes to be a competent developer <em>AT ALL</em>. It&rsquo;s possible that it might make picking up the basics slightly easier, although I&rsquo;m sceptical. Go beyond the first few pages of the Swift guide, and this doesn&rsquo;t feel like a toy language designed specifically for ease of learning.</p>

<p>What Swift doesn&rsquo;t do is lower the bar to understanding the paradigms, the frameworks, or the environment. In fact I&rsquo;d argue it actually <em>raises</em> the bar, at least for a while. It will probably be several years before you can fully get to grips with iOS without <em>any</em> knowledge of ObjectiveC, so for the interim you&rsquo;re going to need to learn the details of two languages if you&rsquo;re just starting out.</p>

<p>It might make building some chunks of functionality quicker, and you might find the syntax more expressive or the structure clearer to read.</p>

<p>But without knowing the abstract concepts of programming, and the details of Cocoa Touch, and the constraints of tiny screens in a world of continuous partial attention, you&rsquo;re not going to succeed in this industry. So I&rsquo;m not going to worry about being priced out of my chosen field just yet.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Cowardly Test-Phobe's Guide to iOS Testing: Networks]]></title>
    <link href="http://adoptioncurve.net/archives/2014/05/the-cowardly-test-phobes-guide-to-ios-testing-networks"/>
    <updated>2014-05-29T15:20:00+01:00</updated>
    <id>http://adoptioncurve.net/archives/2014/05/the-cowardly-test-phobes-guide-to-ios-testing-networks</id>
    <content type="html"><![CDATA[<p><em>(This is the second part of a text-based version of the talk I gave for <a href="https://skillsmatter.com/conferences/1984-ioscon-2014">iOS Con at Skillsmatter</a> in London on Friday 16th May. If you prefer the full multimedia experience, there&rsquo;s video available behind a login wall at <a href="https://skillsmatter.com/skillscasts/5167-tdd-in-ios">https://skillsmatter.com/skillscasts/5167-tdd-in-ios</a>.)</em></p>

<p><em>The presentation slides are <a href="http://www.slideshare.net/timd/the-cowardly-testophobes-guide-to-testing">available here</a>.</em></p>

<h2>Testing networks</h2>

<p>Unless you&rsquo;re in the business of writing fairly trivial apps, eventually your code is going to need to talk to some external services reachable across a network link. That immediately opens up a whole world of problems that you need to deal with. Availability, latency, and quality of service are the issues that your app is going to have to handle, while you&rsquo;re also going to need to make decisions about how to inform your user of what is going on.</p>

<p>It&rsquo;s very easy to fall into the trap of building apps that work beautifully in the Simulator when sat on a Gigabit ethernet segment downstream from a multi-megabit fibre broadband connection. But the real world isn&rsquo;t like that - your app needs to be able to handle the flakiest of ropey Edge services, not just full-fat wifi. Forgetting to handle those edge cases is a quick way to build something with really sucky user experiences.</p>

<p>It (should) go without saying that this needs to be tested. But that can be tricky - very often the APIs that your app is talking to aren&rsquo;t under your control. They&rsquo;re designed to be reliable and return valid data - so how can you test for the edge cases?</p>

<p>There are a couple of solutions, both of which rely on creating &ldquo;stunt double&rdquo; APIs that can stand in for the real thing. By tweaking your mock API, you can develop and test both happy paths and edge cases without any dependencies on live services.</p>

<h2>Mocking APIs with servers</h2>

<p>If you&rsquo;re dealing with a relatively trivial API, the simplest option may be to whip up a standalone server and point your app at that for testing purposes. If you know Sinatra or Node, creating a mock API that accepts calls from your app and returns the contents of some predefined data files stored locally to the server isn&rsquo;t that difficult.</p>

<p>But that a) presupposes that you <em>do</em> have those kind of technologies at your disposal, and b) creates another set of dependencies. In order to run the tests, you&rsquo;ll need to make sure that your server is up and running, and returning the right values for a given endpoint. What would be far more elegant is a situation where <em>all</em> the moving parts needed for testing could somehow be bundled into your Xcode project.</p>

<p>Then you also need to make sure that your tests are calling the test API, while your live app talks to the production version. You don&rsquo;t need too much imagination to see what could potentially go wrong here&hellip;</p>

<h2>Mocking APIs</h2>

<p>A practical alternative to a standalone server is a network stubbing library. That sits inside your test target and intercepts any calls to the network in order to return data that you define. One of the most widely used is <a href="https://github.com/AliSoftware/OHHTTPStubs">OHHTTPStubs</a>.</p>

<p>OHHTTPStubs works by catching calls from <code>NSURLConnection</code> and <code>NSURLSession</code>, and checking whether the request should either be passed through as normal or intercepted by the library. If the call is to be intercepted, the library handles creating and returning the data - the call doesn&rsquo;t get out to the actual network.</p>

<p>There&rsquo;s also the ability to manipulate the way the response is sent back - for example, setting a simulated delay or latency, returning custom HTTP headers or response codes, or just behaving as if all the packets were dropped. By changing responses, it becomes possible to test a variety of situations ranging from perfect network connectivity to complete isolation.</p>

<h3>Setting up OHHTTPStubs</h3>

<p>OHHTTPStubs is easiest to install using Cocoapods. Add <code>pod 'OHHTTPStubs'</code> to your <code>Podfile</code>, run <code>pod install</code>, and you&rsquo;re good to go.</p>

<p>However, now is a good point to introduce a caveat. The library makes extensive use of private frameworks to swizzle the functionality into place, so including it in an app that you try to ship to the App Store is a Very Bad Idea Indeed. There are a couple of ways around this: one is to remember to take it out (not recommended); the other is to only include the library in your test target.</p>

<p>Assuming your project is called <code>MyFantasticApp</code>, then your <code>Podfile</code> should look like this:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>platform :ios, "7.1"
</span><span class='line'>
</span><span class='line'>...
</span><span class='line'>main pods go here
</span><span class='line'>...
</span><span class='line'>
</span><span class='line'>target 'MyFantasticAppTests', :exclusive =&gt; true do
</span><span class='line'>
</span><span class='line'>    pod 'OHHTTPStubs'
</span><span class='line'>
</span><span class='line'>    ...
</span><span class='line'>    other pods as required
</span><span class='line'>    ...
</span><span class='line'>
</span><span class='line'>end</span></code></pre></td></tr></table></div></figure>


<p>As the <code>MyFantasticAppTests</code> target is separate from the main one, <code>OHHTTPStubs</code> won&rsquo;t get compiled in when you build the project.</p>

<h3>How it works</h3>

<p>The basic syntax of using <code>OHHTTPStubs</code> looks like this:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
</span><span class='line'>
</span><span class='line'>   &lt; test the request to see if we want to stub it, and
</span><span class='line'>     and return YES if we do &gt;
</span><span class='line'>
</span><span class='line'>} withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) {
</span><span class='line'>
</span><span class='line'>    &lt; Create and return an OHHTTPStubsResponse object with the
</span><span class='line'>      data that we want to return &gt;
</span><span class='line'>
</span><span class='line'>}];</span></code></pre></td></tr></table></div></figure>


<h4>Which request to stub?</h4>

<p>In the first block, we&rsquo;re examining the <code>NSURLRequest</code> to see if it&rsquo;s one we want to stub out - this allows you to pass through some requests, but catch others.</p>

<p>If you want to stub ALL requests, you simple return YES from this block.  Otherwise, you can be more subtle:</p>

<ul>
<li>catching all requests to a specific host:</li>
</ul>


<p> <code>// Catch http://adoptioncurve.net
</code>return [request.URL.host isEqualToString:@&ldquo;adoptioncurve.net&rdquo;];`</p>

<ul>
<li>catching all requests to a specific URL:</li>
</ul>


<p> <code>// catch http://adoptioncurve.net/about
</code>return [request.URL.lastPathComponent isEqualToString:@&ldquo;about&rdquo;];`</p>

<ul>
<li>catching requests with a specific query string</li>
</ul>


<p> <code>// Catch http://adoptioncurve.net/login?id=1234
</code>return [request.URL.query isEqualToString:@&ldquo;id=1234&rdquo;];`</p>

<h4>How to return data</h4>

<p>Once the <code>stubRequestsPassingTest:</code> block has returned <code>YES</code>, you&rsquo;ll need to create an <code>OHHTTTPStubsResponse</code> object to return to the method that made the original request.  This mimics the data payload that the API would return.</p>

<p>There are several ways of doing this:</p>

<ul>
<li><p><code>responseWithData:statusCode:headers:</code> allows you to create an NSData object yourself, and return it along with an HTTP status code and HTTP headers</p></li>
<li><p><code>responseWithFileAtPath:statusCode:headers:</code> allows the contents of a file to be returned, along with status codes and headers. This file can be JSON, HTML, binary data or whatever format your API will return - the only requirement is that it exists in the app bundle where the tests can find it.</p></li>
</ul>


<h3>Getting sample data</h3>

<p>The first thing you&rsquo;ll need when starting to use <code>OHHTTPStubs</code> is some data to return for your tests.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Loading a Storyboard Programatically]]></title>
    <link href="http://adoptioncurve.net/archives/2014/05/loading-a-storyboard-programatically"/>
    <updated>2014-05-25T21:33:00+01:00</updated>
    <id>http://adoptioncurve.net/archives/2014/05/loading-a-storyboard-programatically</id>
    <content type="html"><![CDATA[<p>I am not the world&rsquo;s greatest fan of Storyboards, having been scarred by an unfortunate project involving a) a huge Storyboard b) multiple developers and c) horrific merge conflicts. That said, some people do like them, so each to their own&hellip;</p>

<p>If you manage to overcome the visceral loathing and need to user Storyboards in tests, you&rsquo;ll hit the problem that they seem to be used semi-magically. There&rsquo;s no obvious equivalent of an <code>initWithNibFile</code> method that you can hook into to load the thing as you kick your test case off.</p>

<p>The answer is actually reasonably straight forward. Create your storyboard as normal (or rely on an Xcode template if that&rsquo;s your thing), then make sure that you&rsquo;ve given it a <code>Storyboard ID</code> in the Attributes inspector. The ID you use is a text string, and Xcode doesn&rsquo;t seem to care what that string is.</p>

<p>Then in your test, you load and instantiate your view controller in a two stage process - here&rsquo;s an example Kiwi test:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='objc'><span class='line'><span class="n">it</span><span class="p">(</span><span class="s">@&quot;should instantiate the view controller&quot;</span><span class="p">,</span> <span class="o">^</span><span class="p">{</span>
</span><span class='line'>    <span class="bp">UIStoryboard</span> <span class="o">*</span><span class="n">mainStoryboard</span> <span class="o">=</span> <span class="p">[</span><span class="bp">UIStoryboard</span> <span class="nl">storyboardWithName</span><span class="p">:</span><span class="s">@&quot;Main&quot;</span> <span class="nl">bundle</span><span class="p">:</span><span class="nb">nil</span><span class="p">];</span>
</span><span class='line'>    <span class="n">ViewController</span> <span class="o">*</span><span class="n">vc</span> <span class="o">=</span> <span class="p">[</span><span class="n">mainStoryboard</span> <span class="nl">instantiateViewControllerWithIdentifier</span><span class="p">:</span><span class="s">@&quot;ViewController&quot;</span><span class="p">];</span>
</span><span class='line'>    <span class="p">[[</span><span class="n">vc</span> <span class="n">shouldNot</span><span class="p">]</span> <span class="n">beNil</span><span class="p">]</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>This loads the storyboard itself, then instantiates the view controller from it - the identifier string is whatever you put in the <code>Storyboard ID</code> field in Interface Builder.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Cowardly Test-o-Phobe's Guide to iOS Testing]]></title>
    <link href="http://adoptioncurve.net/archives/2014/05/the-cowardly-test-o-phobes-guide-to-ios-testing"/>
    <updated>2014-05-25T17:48:00+01:00</updated>
    <id>http://adoptioncurve.net/archives/2014/05/the-cowardly-test-o-phobes-guide-to-ios-testing</id>
    <content type="html"><![CDATA[<p><em>(This is the first part of a text-based version of the talk I gave for <a href="https://skillsmatter.com/conferences/1984-ioscon-2014">iOS Con at Skillsmatter</a> in London on Friday 16th May. If you prefer the full multimedia experience, there&rsquo;s video available behind a login wall at <a href="https://skillsmatter.com/skillscasts/5167-tdd-in-ios">https://skillsmatter.com/skillscasts/5167-tdd-in-ios</a>.)</em></p>

<p><em>The presentation slides are <a href="http://www.slideshare.net/timd/the-cowardly-testophobes-guide-to-testing">available here</a>.</em></p>

<h2>Why is testing scary?</h2>

<p>Unit testing is a topic that gets talked about a <strong>lot</strong>, but if you&rsquo;re not a computer scientist it can have a tricksy reputation. It doesn&rsquo;t help that much of the source material available is Java-based. That&rsquo;s fine if you like Java - I&rsquo;m personally not so keen - but there&rsquo;s a lot less help if your primary weapon of choice is Objective-C.</p>

<p>Testing is also a topic that attracts - how shall we put it? - some of the more tedious personalities in this business. There&rsquo;s nothing so dull as a self-appointed &ldquo;thought leader&rdquo;, and a lot of what passes for debate on testing is so much arcane, &ldquo;how many angels can dance on the head of a pin&rdquo;-style nonsense.</p>

<p>That&rsquo;s got very little to do with the day-to-day grind of shipping software. There is no One Way to do this, and if you look hard enough at the motives of those who would have you believe that, you often find it comes down to selling themselves as a brand.</p>

<h2>Why is testing important?</h2>

<p>All that said, testing <strong>is</strong> important. Let&rsquo;s start from the premise that the fewer bugs in your code, the better. If you subscribe to that school of thoughy, then anything that helps you achieve this has to be a good thing. As the developer who writes 100% bug-free code hasn&rsquo;t been born yet, we&rsquo;re also faced with the challenge that the more code we write, the more likely it is that the project will turn out to be infested with them.</p>

<p>Documentation is also held to be a Good Thing, but it&rsquo;s also something that very few devs are particularly keen on doing - especially once the code&rsquo;s been written.  A comprehensive test suite, especially if it&rsquo;s been built using one of the more &ldquo;descriptive&rdquo; tools such as Kiwi or Specta, can almost replace documentation. It&rsquo;s also considerably easier to read than code, because it&rsquo;s documenting <em>intent</em> rather than <em>execution</em> - the &ldquo;what&rdquo; rather than the &ldquo;how&rdquo;.</p>

<p>Perhaps the most important reason for taking a test-driven approach, though, is the way you&rsquo;ll knit yourself a &ldquo;security blanket&rdquo; around your code. We&rsquo;ve all been in the situation where making changes to an existing code base is a stressful affair, because you&rsquo;re never quite sure whether changing something over <em>here</em> will break something over <em>there</em>.</p>

<p>If your test suite is comprehensive enough, you can relax to an extent knowing that the tests will catch those kinds of problem. And that becomes particlarly important if you&rsquo;re working with others, because tests can help catch things that break <em>your</em> code.</p>

<!-- more -->


<h2>The basics</h2>

<p>The basic purpose of testing is to ask the question <em>&ldquo;does my code do what it&rsquo;s supposed to do.&rdquo;</em> Assuming that you can give a positive answer to that, it will then help you to ask other, more probing questions. *&ldquo;Can my code handle unexpected values?&rdquo; is one of them. Coding for the &ldquo;happy path&rdquo; only is a common problem - how can you ensure that your app will still work if the API doesn&rsquo;t respond, for example. What will happen if the data received back from the API is beyond the bounds you expected, or is corrupt?</p>

<p>Even if your code is capable of handling strange data, you can still end up creating problems for yourself further down the line. As you add more classes and features, the chances of something new breaking something existing multiplies. Protecting each area with tests means that you have a safety net that should catch problems by code in another part of the app.</p>

<h2>Why not test last?</h2>

<p>The meaning of the word &ldquo;test&rdquo; implies checking after the fact - making sure that the code you&rsquo;re written functions as you expected it to do. The problem with testing code <em>after</em> you&rsquo;ve written it is that there&rsquo;s actually very little motivation to do this in normal circumstances. After all, you&rsquo;ve written the code, it does what it&rsquo;s supposed to, and you&rsquo;re infallible - right? Testing that it works is just spending more time doing over the same ground.</p>

<p>That&rsquo;s definitely the response you&rsquo;ll get when the project manager wanders over and asks what you&rsquo;re doing. If the answer is &ldquo;writing tests for the feature that we shipped last week&rdquo;, then they&rsquo;re going to ask when you&rsquo;re going to get on with more productive stuff. In a time-constrained project, there&rsquo;s a perverse incentive <em>not</em> to test.</p>

<h2>Why test first?</h2>

<p>The rhythm of test-first, or test-driven development follows a predictable pattern. First, you write a test which describes the outcome that you&rsquo;re after. What that will be obviously depends on the type of code you&rsquo;re writing - in the case of a calculation, it would be a correct result; in the case of a UI feature it would be some kind of update to the views.</p>

<p>Then, you run the test. This seems counter-intuitive, because it fails.  It has to fail, after all - you haven&rsquo;t written any code to make it pass yet. In the jargon, your test has just <em>&ldquo;gone red&rdquo;</em>. But in the process of seeing the test fail, you&rsquo;re already getting clues about how to go about fixing it. It&rsquo;s like having a small and benign homunculus perched on your shoulder, whispering hints about what to do as the tests progress.</p>

<p>With that advice in mind, you can then write the code that will make the test pass - or <em>&ldquo;go green&rdquo;</em>. If at first the test fails, you know you haven&rsquo;t got it right yet - but you always have the target in mind, because you started by describing the outcome that you were looking for.</p>

<p>Once you&rsquo;ve got a passing test, you&rsquo;re then free to improve things safe in the knowledge that the test will catch anything you do to break the code. That&rsquo;s the &ldquo;refactor&rdquo; step, and you&rsquo;ve now been once round the <em>red-green-refactor</em> loop that is the basic process of test-driven development.</p>

<h2>Challenges of testing iOS</h2>

<p>Test-driven development, or indeed testing of any kind, has some special challenges in the iOS world. The tools and techniques of testing were developed in a terminal-driven world, so many of the approaches are predicated on the results being something that has no user interface component.</p>

<p>On iOS, on the other hand, practically everything happens in response to some kind of user input passed down through the Cocoa Touch layer. And the code that responds to the touches can be highly modular - an indidivual class rarely stands and operates on its own, but instead has to collaborate with all manner of other classes and external APIs.</p>

<p>These two factors - responding to touches, and highly-modular code architectures - can make test-driven development on iOS seem like an impossible challenge.  That&rsquo;s even more the case if you&rsquo;ve inherited an existing project, and you&rsquo;re now faced with the challenge of wrapping tests around an already-built code base.</p>

<p>Fortunately, there are some available tools and techniques which can get around both these problems. In the next post, I&rsquo;ll dig down into how these work in practice, and how you can take advantage of the structure of Cocoa Touch itself to build apps in a completely test-driven way.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Creating Image Callouts in Omnigraffle]]></title>
    <link href="http://adoptioncurve.net/archives/2013/11/creating-image-callouts-in-omnigraffle"/>
    <updated>2013-11-18T14:51:00+00:00</updated>
    <id>http://adoptioncurve.net/archives/2013/11/creating-image-callouts-in-omnigraffle</id>
    <content type="html"><![CDATA[<p>Here&rsquo;s a quick way of drawing a enlarged callout on an image using Omnigraffle.</p>

<p><img src="http://adoptioncurve.net/images/2013/11/stage2-7.png"></p>

<p>To avoid pixellation in the callout, your original image will need to be bigger than the main image on the canvas.  Place the main image on the canvas and scale it accordingly:</p>

<p><img src="http://adoptioncurve.net/images/2013/11/stage1-1.png"></p>

<p>Draw a circle shape onto the canvas, then add another copy of the main image as the shape&rsquo;s background using the <code>Set Image</code> option in the <code>Image</code> section in the inspector:</p>

<p><img src="http://adoptioncurve.net/images/2013/11/stage2-1.png"></p>

<p>A scaled-down version of the main image will appear as the background of the callout shape:</p>

<p><img src="http://adoptioncurve.net/images/2013/11/stage2-2.png"></p>

<p>Now click the <code>Manual Sizing</code> button in the Image inspector to revert the shape background to full size:</p>

<p><img src="http://adoptioncurve.net/images/2013/11/stage2-3.png"></p>

<p>Then click the <code>Mask</code> button so that the shape is shown as an overlay on the fullsize image:</p>

<p><img src="http://adoptioncurve.net/images/2013/11/stage2-4.png"></p>

<p>Now you can use the scaling grab handles at each corner of the shape&rsquo;s background image to get the callout to the correct size, and move it so that the correct area is show in the callout:</p>

<p><img src="http://adoptioncurve.net/images/2013/11/stage2-5.png"></p>

<p>Clicking the <code>Done</code> button in the Image inspector will hide the full background image - at this point you can move the callout into the right place.</p>

<p>To show the zoomed area, drag another Circle shape onto the canvas and set its fill style to none.  Now position it to show the area that&rsquo;s enlarged in the callout.  You can also adjust the border of the circles to make them stand out:</p>

<p><img src="http://adoptioncurve.net/images/2013/11/stage2-6.png"></p>

<p>Finally, add two tangent lines to join the original area and the callout:</p>

<p><img src="http://adoptioncurve.net/images/2013/11/stage2-7.png"></p>

<p>The end result is a neat callout image highlighting a specific area on the main image.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Universal Principles]]></title>
    <link href="http://adoptioncurve.net/archives/2013/11/universal-principles"/>
    <updated>2013-11-18T09:48:00+00:00</updated>
    <id>http://adoptioncurve.net/archives/2013/11/universal-principles</id>
    <content type="html"><![CDATA[<p>The <a href="https://www.gov.uk/government/organisations/cabinet-office">UK Cabinet Office</a> is using <a href="http://digital.cabinetoffice.gov.uk">GDS</a> to run a technology transformation programme, <a href="https://cabinetofficetechnology.blog.gov.uk/2013/11/13/technology-at-least-as-good-as-people-have-at-home/">according to their blog</a>.  They&rsquo;ve published the guiding principles that they&rsquo;re using - and they&rsquo;re sufficiently flexible to apply pretty much anywhere. Replace specific mentions of government with the sector of your concern, and they&rsquo;re equally applicable:</p>

<blockquote><p>Our guiding principles over the next 12-18 months include the following:</p><p>* we will start with user needs: until we understand what users across the Cabinet Office want and need, we won’t start buying things</p><p>* we will design with choice and flexibility in mind: there will be many and different needs across the department so we will offer technology solutions that fit individuals and teams</p><p>* we will be transparent throughout: we will be open about decisions and actions so our users and stakeholders understand why we’re taking a certain approach</p><p>* we will architect loosely coupled services: we are not building a “system”; we are delivering a set of devices and services that can be independently replaced. A key success measure for the programme is that we should never have to do it again</p><p>* we will favour short contracts: technology changes rapidly and we believe the age of the long-term contract is over. We need to be able to swap services in and out as the need arises</p><p>* we will bring the best of consumer technology to the enterprise: modern devices and cloud applications are built to be intuitive and flexible with minimal need for training. We believe business technology should be the same</p><p>* we will make security as invisible as possible: we are working with CESG and GSS to ensure all services are secure to new Official level. However, appropriate levels of security shouldn’t get in the way of the user experience of the services</p><p>* we will build a long-term capability: technology delivery doesn’t end with the programme. We will not be handing the services over to a single outsource vendor in 2015, but instead will be bringing digital skills back into the department</p></blockquote>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Introducing ActsAsBeacon]]></title>
    <link href="http://adoptioncurve.net/archives/2013/11/introducing-actsasbeacon"/>
    <updated>2013-11-09T16:18:00+00:00</updated>
    <id>http://adoptioncurve.net/archives/2013/11/introducing-actsasbeacon</id>
    <content type="html"><![CDATA[<p>iOS7 introduces support for Bluetooth LE (aka Bluetooth Smart). “LE” stands for Low Energy – a Bluetooth LE device has an incredibly low current draw, which means it can potentially operate for extended periods (think months) on nothing more than a coin cell battery.</p>

<p>Apple are using Bluetooth LE to power iBeacons – a beacon is a low-power device that talks Bluetooth LE and can be detected by the CoreLocation stack. An app can be “woken up” by a beacon, and can use the signals from several beacons to obtain location information. Think indoor GPS with a (potential) accuracy of centimetres.</p>

<p>At the moment, the iBeacon spec is under NDA, which means that beacons themselves are hard to come by. You can pre-order Estimotes which look like they’ll be the simple, pretty but expensive option; or try Kontakt devices (not so pretty, still expensive). Or there’s the Redbear Labs BLE Mini if you prefer bare boards and some soldering.</p>

<p><img src="http://adoptioncurve.net/images/2013/11/actsasbeacon.png" width="250"></p>

<p>iOS devices of recent vintage can act as beacons, though – so if you just need some beacons for testing, there’s no reason why you can’t grab a handful of iPod Touches or similar and use these. The other advantage of this approach is that configuring the various beacon parameters is much easier with a iOS device than fiddling around with hardware alternatives.</p>

<p><a href="https://github.com/timd/ActsAsBeacon">ActsAsBeacon</a> is a tiny app which turns your iOS7 device into an iBeacon, and has a search function to show details of beacons in the vicinity. It will also allow you to configure the service UUID and broadcast parameters so that it’s possible to experiment with iBeacon-enabled apps.</p>

<p>In the next version that I’m currently tinkering with, the app will also provide a configuration interface for BLE Mini boards – Redbear Labs have an app for this, but it’s a bit broken on iOS7. My version allows the Mini boards to be configured over the air once their firmware has been updated to run the iBeacon version.</p>

<p>The app’s available as a GitHub repo, and I’ll be submitting a version to the App Store in a couple of days so that there’s no dependency on Xcode and a Developer Program license.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Removing Storyboards From Xcode 5's Default Single View App Template]]></title>
    <link href="http://adoptioncurve.net/archives/2013/10/removing-storyboards-from-xcode-5-s-default-single-view-app-template"/>
    <updated>2013-10-06T13:46:00+01:00</updated>
    <id>http://adoptioncurve.net/archives/2013/10/removing-storyboards-from-xcode-5-s-default-single-view-app-template</id>
    <content type="html"><![CDATA[<p>The new default single-view application template in Xcode 5 is based on Storyboards rather than the previous view-controller-and-nib-files approach.  That&rsquo;s fine if you like Storyboards, but I don&rsquo;t - so the first thing I do when starting a new project is rip them out and replace them with the old approach.</p>

<p>This is by way of an outboard brain dump to remind myself of how this is done.</p>

<h3>Remove the Main.storyboard file</h3>

<p>This can simply be deleted.</p>

<h3>Update the ProjectName-Info.plist file</h3>

<p>Remove the <code>Main storyboard base file name</code> key.</p>

<h3>Create a nib file and link to the project&rsquo;s view controller</h3>

<ol>
<li>Create a nib file (File -> New -> File -> View)</li>
<li>Update the <code>File's Owner's</code> class to whatever the project&rsquo;s view controller is called</li>
<li>Link the <code>File's Owner's</code> <code>view</code> outlet to the <code>view</code> object in the nib file</li>
</ol>


<h3>Update the app delegate</h3>

<ol>
<li>Import the project&rsquo;s view controller&rsquo;s header file</li>
<li>Update the <code>application:didFinishLaunchingWithOptions:</code> method:</li>
</ol>


<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='objc'><span class='line'><span class="p">-</span> <span class="p">(</span><span class="kt">BOOL</span><span class="p">)</span><span class="nf">application:</span><span class="p">(</span><span class="bp">UIApplication</span> <span class="o">*</span><span class="p">)</span><span class="nv">application</span> <span class="nf">didFinishLaunchingWithOptions:</span><span class="p">(</span><span class="bp">NSDictionary</span> <span class="o">*</span><span class="p">)</span><span class="nv">launchOptions</span> <span class="p">{</span>
</span><span class='line'>    <span class="c1">// Override point for customization after application launch.</span>
</span><span class='line'>    <span class="nb">self</span><span class="p">.</span><span class="n">window</span> <span class="o">=</span> <span class="p">[[</span><span class="bp">UIWindow</span> <span class="n">alloc</span><span class="p">]</span> <span class="nl">initWithFrame</span><span class="p">:[[</span><span class="bp">UIScreen</span> <span class="n">mainScreen</span><span class="p">]</span> <span class="n">bounds</span><span class="p">]];</span>
</span><span class='line'>    <span class="n">MyViewController</span> <span class="o">*</span><span class="n">viewController</span> <span class="o">=</span> <span class="p">[[</span><span class="n">MyViewController</span> <span class="n">alloc</span><span class="p">]</span> <span class="nl">initWithNibName</span><span class="p">:</span><span class="s">@&quot;MyViewController&quot;</span> <span class="nl">bundle</span><span class="p">:</span><span class="nb">nil</span><span class="p">];</span>
</span><span class='line'>    <span class="nb">self</span><span class="p">.</span><span class="n">window</span><span class="p">.</span><span class="n">rootViewController</span> <span class="o">=</span> <span class="n">viewController</span><span class="p">;</span>
</span><span class='line'>    <span class="p">[</span><span class="nb">self</span><span class="p">.</span><span class="n">window</span> <span class="n">makeKeyAndVisible</span><span class="p">];</span>
</span><span class='line'>    <span class="k">return</span> <span class="nb">YES</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>

]]></content>
  </entry>
  
</feed>
