<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Oliver Dew on Medium]]></title>
        <description><![CDATA[Stories by Oliver Dew on Medium]]></description>
        <link>https://medium.com/@oli_d?source=rss-74a87d8a3d3d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ehVvUCeexNrsb7Bz.jpg</url>
            <title>Stories by Oliver Dew on Medium</title>
            <link>https://medium.com/@oli_d?source=rss-74a87d8a3d3d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 22:01:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oli_d/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Foundation re-formatted]]></title>
            <link>https://medium.com/kinandcartacreated/foundation-re-formatted-862a4db1b941?source=rss-74a87d8a3d3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/862a4db1b941</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[parsing]]></category>
            <category><![CDATA[formatting]]></category>
            <category><![CDATA[foundation]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Oliver Dew]]></dc:creator>
            <pubDate>Fri, 17 Mar 2023 16:17:47 GMT</pubDate>
            <atom:updated>2023-03-17T16:17:47.611Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6vIsMu6Erg4jufghtiZ1_Q.jpeg" /><figcaption>Photo credit: <a href="https://www.pexels.com/photo/close-up-of-a-cable-car-323645/">Karol D on Pexels</a></figcaption></figure><p>Apple developers have long been able to use a rich set of Formatter objects to ensure that numbers, currencies, dates, measurements, lists, personal names, URLs and so on are correctly formatted for a given locale and context, and to enable parsing such objects from strings. The iOS 15/ macOS 12 release of Foundation however brought with it a whole new paradigm for handling this kind of formatting and parsing. Instead of having to instantiate and manage the lifecyle of aFormatter class, we can now handle this parsing and formatting via a more declarative API that involves chaining a set of methods on a struct that implements the ParseableFormatStyle protocol, composing the formatter in a fluent/ builder pattern that is becoming increasingly familiar thanks to its extensive use in SwiftUI. There have been some great overviews of these new APIs. Rather than try to give an overview of all of the new formatting APIs, this blogpost is just going to home in on one use-case where the move from the old object-oriented Formatter to the new declarative paradigm really shines.</p><h3>Date-only ISO 8601</h3><p>Take the use-case of decoding some JSON from a network service which has dates that look like this: &quot;2023-12-25&quot;. The endpoint in question is a list of public holidays in the UK: <a href="https://www.gov.uk/bank-holidays.json">https://www.gov.uk/bank-holidays.json</a>. These dates are formatted as ISO-8601, but a subset of the standard that provides only the date, not the time or any timezone information. Although JSONDecoder has an iso8601 DateDecodingStrategy, it expects to receive the time as well as the date, and will fail to decode date-only strings.</p><p>So, we need to supply a custom DateDecodingStrategy. JSONDecoder.DateDecodingStrategy uses a closure-based API for supplying custom date decoding. Let’s start by decoding the date as a string in the custom decoding closure:</p><pre>let decoder = JSONDecoder()<br>decoder.dateDecodingStrategy = .custom { decoder in<br>    let dateString = try String(from: decoder)<br>    ...<br>}</pre><p>Now we need to parse that string as a date. Let’s first look at how we would have handled this using the old Formatter API. First we would set up a Formatter object and set the correct options for the dates we expect to arrive from the endpoint:</p><pre>let formatter = ISO8601DateFormatter()<br>formatter.formatOptions = .withFullDate</pre><p>By replacing the default format options with .withFullDate, we’ve told the formatter to expect date-only strings.</p><p>With this object-based API, we need to think about how to manage the lifecyle of our formatter. We almost certainly don’t want to place these two lines of code inside the custom date decoding block: this block will get called to decode every date in the JSON response, and given that the date formatter ultimately descends from NSObject, it’s quite an expensive object to be repeatedly instantiating. So we probably want to instantiate it outside the block, and dispose of it once the response has finished decoding:</p><pre>let formatter = ISO8601DateFormatter()<br>formatter.formatOptions = .withFullDate<br>let decoder = JSONDecoder()<br>decoder.dateDecodingStrategy = .custom { decoder in<br>    let dateString = try String(from: decoder)<br>    guard let date = formatter.date(from: dateString) else {<br>        let context = DecodingError.Context(codingPath: decoder.codingPath, debugDescription: &quot;Date is not ISO8601&quot;)<br>        throw DecodingError.dataCorrupted(context)<br>    }<br>    return date<br>}</pre><p>There are a couple of bits of housekeeping we have to deal with here. Firstly, the old Formatter API doesn’t throw errors, it just returns nil (failing silently in other words). It is up to us then to navigate the DecodingError API to throw the correct error.</p><p>And more worryingly, the compiler complains about the formatter being captured by the closure, with the warning</p><blockquote>Capture of ‘formatter’ with non-sendable type ‘ISO8601DateFormatter’ in a `@Sendable` closure</blockquote><p>We can silence this warning using @unchecked Sendable conformance:</p><pre>extension ISO8601DateFormatter: @unchecked Sendable {}</pre><p>…but wouldn’t it be nice to not have to worry about managing the lifecycle and thread safety of formatting objects at all?</p><h3>In with the new</h3><p>The new formatting APIs can be a little challenging to discover. In place of a set of objects that all descend from Formatter, the new APIs are more diffuse. For formatting an object as a String look for .formatted() methods on Date , Double, Measurement (in iOS 16 also URL) and so on. For parsing from strings, look for initialisers that take a string followed by a strategy or format parameter where you will pass an implementation of the ParseableFormatStyle protocol (not to be confused with initialisers that take a formatter argument, these refer to the old Formatter objects). These parser/ formatter structs are namespaced within the object they parse/ format. In our example, the struct we want is Date.ISO8601FormatStyle. There is also a static variable .iso8601 that we can use to shorten the full type. So to parse a date string in standard ISO8601, we would use Date(dateString, strategy: .iso8601). There is a bit of a discoverability issue here. When faced with the Date(_ value:strategy:) initialiser, in my testing Xcode was unable to infer any code completions for the strategy argument. Working out what to enter for the strategy can be a case of starting with the namespace of the object you’re trying to parse (in this case Date.), seeing what ParseableFormatStyle objects are available, and then seeing if convenient factory methods exist or can be created.</p><p>Confusingly, some objects have both an initialiser with a strategy parameter and one with a format parameter. In my experience it is often more ergonomic to use the format initialiser, which takes a ParseableFormatStyle implementation. Take for example wanting to parse currency strings such as &quot;£40.00&quot; as a Decimal. Note that this is a conversion that requires both a currency code and a locale. In this case Decimal.ParseStrategy actually wraps the format style, so we can omit this wrapper by using the format initialiser. With this initialiser, Xcode can even supply us with code completion suggestions as soon as you enter . in the format field:</p><pre>try Decimal(value, strategy: Decimal.ParseStrategy(format: .localizedCurrency(code: &quot;GBP&quot;, locale: .enGB)))<br>// omiting the `Decimal.ParseStrategy` wrapper:<br>try Decimal(value, format: .localizedCurrency(code: &quot;GBP&quot;, locale: .enGB))</pre><p>The available formatters aren’t always consistent. For instance, if we were wanting to store our currency as a Double instead of a Decimal, FloatingPointFormatStyle does not have a localizedCurrency factory method, so we would instead chain together a currency and a locale call:</p><pre>try Double(value, format: .currency(code: &quot;GBP&quot;).locale(.enGB))</pre><p>If we wanted to have a consistent call-site with the Decimal one, it isn’t too hard to define a static factory method in an extension:</p><pre>extension FloatingPointFormatStyle.Currency {<br>    static func localizedCurrency(code: String, locale: Locale) -&gt; Self {<br>        .currency(code: code).locale(locale)<br>    }<br>}<br><br>// call site:<br>try Double(value, format: .localizedCurrency(code: &quot;GBP&quot;, locale: .enGB))</pre><p>This feature demonstrates the fluent/ builder pattern of the new API. Methods return a modified instance of the same struct, so that we can compose a formatter by chaining several methods together. We’ll now turn to another example of this pattern in the final section of this post.</p><h3>Foundation Re-formatted</h3><p>Returning to our use case of the date-only API, in order to replace the default ISO8601 implementation with one that is date only, we can chain together a string of modifiers on the base ISO 8601 formatter: .iso8601.year().month().day(). These modifiers overwrite the default set of components vended by the ISO 8601 formatter, indicating that we are only interested in year, month and day. Our custom decoder now looks like this:</p><pre>let decoder = JSONDecoder()<br>decoder.dateDecodingStrategy = .custom { decoder in<br>    let dateString = try String(from: decoder)<br>    return try Date(dateString, strategy: .iso8601.year().month().day())<br>}</pre><p>We no longer have to manage the lifecycle of a Formatter object, ensure its threadsafety, or manually compose a DecodingError. To make this custom decoder easy to use wherever I need to interact with this API in my code, I like to add a convenience initialiser to JSONDecoder that takes a DateDecodingStrategy and a factory method that returns our date-only ISO8601 decoder:</p><pre>extension JSONDecoder {<br>    convenience init(dateDecodingStrategy: DateDecodingStrategy) {<br>        self.init()<br>        self.dateDecodingStrategy = dateDecodingStrategy<br>    }<br> <br>    static var iso8601DateOnly = JSONDecoder(dateDecodingStrategy: .custom { decoder in<br>        let dateString = try String(from: decoder)<br>        return try Date(dateString, strategy: .iso8601.year().month().day())<br>    })<br>}</pre><p>The new APIs, particularly when it comes to parsing strings into data, are more diffuse than the Object-Oriented APIs they replace (where everything descends from the Formatter base class). They don’t always feel consistent at the call site. Date only gives us an initialiser that takes a strategy, whereas number types like Decimal give us the choice of strategy and format, with the latter being more ergonomic. As we have seen, different types of ParseableFormatStyle implementations on number types handle localization with slightly different calls. But with certain use cases, like custom JSON decoding, the advantages of moving from an Object-Oriented to a declarative struct-based paradigm are clear.</p><p>Because the new API is struct based we no longer need to worry about the lifecycle of objects, or whether they conform to Sendable and will play nice with async/ await code. And because the new API throws errors instead of silently failing, we don’t have to worry about composing errors like DecodingError by hand.</p><p>In this post we’ve focused on one specific use-case, custom JSON decoders, where taking object lifecycle management out of the equation makes developers’ lives easier. But as Apple increasingly moves away from its Object-Oriented legacy towards declarative and composable APIs (I’m thinking particularly of SwiftUI) there are going to be a growing number of domains where being able to parse and format data without the developer overhead of managing the lifecycles and thread-safety of the formatting objects will pay real dividends.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=862a4db1b941" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kinandcartacreated/foundation-re-formatted-862a4db1b941">Foundation re-formatted</a> was originally published in <a href="https://medium.com/kinandcartacreated">Kin + Carta Created</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Looks great, nice one Pete!]]></title>
            <link>https://medium.com/@oli_d/looks-great-nice-one-pete-f5052b66e33c?source=rss-74a87d8a3d3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5052b66e33c</guid>
            <dc:creator><![CDATA[Oliver Dew]]></dc:creator>
            <pubDate>Fri, 04 Nov 2022 11:03:03 GMT</pubDate>
            <atom:updated>2022-11-04T11:03:03.396Z</atom:updated>
            <content:encoded><![CDATA[<p>Looks great, nice one Pete!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5052b66e33c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Augmenting the workplace with ARKit]]></title>
            <link>https://medium.com/kinandcartacreated/augmenting-the-workplace-with-arkit-f65c1f50b67a?source=rss-74a87d8a3d3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f65c1f50b67a</guid>
            <category><![CDATA[arkit]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[ar]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Oliver Dew]]></dc:creator>
            <pubDate>Thu, 21 Jun 2018 14:51:47 GMT</pubDate>
            <atom:updated>2018-06-22T13:53:47.228Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qTJx9DHNTNDPUXTEUGF3Fw.jpeg" /><figcaption>Hanging a virtual painting: <a href="https://sketchfab.com/models/e6d25ffb257a426dab5cf7767eb86900#">“Bird Snowing Again” by Guido Salimbeni</a></figcaption></figure><p>Apple’s ARKit does a fantastic job of anchoring virtual objects in the real world. This illusion of a coherent augmented space collapses though if a real-world object passes <em>in-between</em> the device’s camera and the virtual object: the AR object remains fully visible onscreen with the real-world object appearing to pass beneath it, despite the real object being closer to the user.</p><p>Imagine an app that turns any surface into a whiteboard. What would happen if, as you moved through your augmented office, all your jotted-down notes continued to be visible, even if they were behind a wall, or in another room? You would quickly be faced with a confusing jumble of overlapping notes and drawings filling the visual field. How can we make these virtual notes and drawings disappear behind walls and other surfaces just like their real-life counterparts would?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F274723381%3Fapp_id%3D122963&amp;dntp=1&amp;url=https%3A%2F%2Fvimeo.com%2F274723381&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F706823482_1280.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1280" height="720" frameborder="0" scrolling="no"><a href="https://medium.com/media/d91c7ff5980730ffd7e7f08f0bf39190/href">https://medium.com/media/d91c7ff5980730ffd7e7f08f0bf39190/href</a></iframe><p>To make it appear as if AR objects are passing behind real world ones, we need to be able to track the surface of those blocking objects, and use those surfaces to mask off sections of the virtual scene. We can call these masking objects “occlusion geometry”.</p><p>When ARKit 1.5 arrived in iOS 11.3 earlier this year, Apple gave us a couple of new features that make this easier. First, they expanded ARKit’s plane detection capabilities so that they can detect vertical planes in addition to horizontal ones, allowing us to detect walls. Second, ARKit 1.5 gives us more precise information about the shape of those planes. Whereas version 1 of ARKit represented planes as rectangles, ARKit 1.5 can represent planes as convex polygons, more closely tracking the shape of surfaces. We also get a new geometry primitive in SceneKit that can be dynamically updated as fresh information about the plane is found. A quick search of Twitter and StackOverflow shows lots of <a href="https://twitter.com/codePrincess/status/1006159916904611840">people experimenting </a>with <a href="https://stackoverflow.com/questions/44893320/arkit-hide-objects-behind-walls">these techniques</a>, so I was keen to see what was possible for myself.</p><h4>Wall detection</h4><p>Without any rear-facing depth sensors in current hardware, ARKit relies on there being discernible, relatively high contrast features in the scene that it can lock on to. If your workplace is all smoothly plastered walls, you’re flat out of luck. Point it at a patterned or textured surface such as tiles or exposed brick however, and it’ll start picking up patches of the surface quite quickly, expanding the area of the known surface as the camera pans around.</p><p>For rendering virtual content in the AR scene, there are several choices of engine. ARKit bridges to the third-party game engines Unity and Unreal, and also to Apple’s own Metal and SceneKit frameworks. If you wish to avoid third-party dependencies, or prototype rapidly, SceneKit is a great choice.</p><p>Xcode 9 provides a handy ARKit/ SceneKit template to kick things off. The first step is to enable plane detection in an ARKit world-tracking session:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/303ac33f29d17ca69e0eaf945d311419/href">https://medium.com/media/303ac33f29d17ca69e0eaf945d311419/href</a></iframe><p>What information do we then get back about the surfaces that ARKit detects? ARKit refers to fixed points of interest in the scene as anchors, and when bridging to SceneKit, each anchor can be represented as a node in SceneKit’s object graph. ARSCNViewDelegate has a set of methods that we can implement to find out whenever an anchor/ node pair has been added, updated, or removed from the scene. Let’s look at how we handle nodes being added to the scene in the renderer:nodeForAnchor: method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/628c829a9395cfdf8d6efaeda3305bee/href">https://medium.com/media/628c829a9395cfdf8d6efaeda3305bee/href</a></iframe><p>Let’s unpack this method line-by-line. Because we’re only interested in planes, we cast ARAnchor to ARPlaneAnchor. New in ARKit 1.5, the plane anchor in turn has a geometry property of type ARPlaneGeometry. This progression gradually gives us more information about the plane. ARAnchor gives us a 4x4 transformation matrix that tells us the anchor location and orientation. ARPlaneAnchor then gives us the smallest rectangle that will enclose the plane. ARPlaneGeometry gives us richer details, describing the smallest convex polygon that encloses the feature points that make up the plane.</p><p>One point of interest is that ARKit defines the plane’s orientation in such a way that the “up” axis of its transformation matrix is perpendicular to the plane (it is the plane’s “normal”). So if you’re wanting to hang a piece of virtual art on a wall using the plane’s transformation matrix, you’ll have to orient the artwork so that it’s laying on its back.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F276447436%3Fapp_id%3D122963&amp;dntp=1&amp;url=https%3A%2F%2Fvimeo.com%2F276447436&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F708976288_1280.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1080" frameborder="0" scrolling="no"><a href="https://medium.com/media/18f2829c698abce675160b5f488682bc/href">https://medium.com/media/18f2829c698abce675160b5f488682bc/href</a></iframe><h4>A quick coat of invisibility paint</h4><p>To quickly visualise the surfaces that ARKit has detected, we can use the new ARSCNPlaneGeometry class. In my testing I found that this class crashes unless it has a Metal device set (we’ll file a radar with Apple). We can retrieve the Metal device from the SceneKit renderer. Note that for this line to compile, the build target cannot be a simulator, as the simulator does not yet support Metal. To continue, change your build target to a real device.</p><p>We now have geometries in our scene corresponding to the surfaces that ARKit has detected. How do we then use these geometries to mask areas of our scene? The secret sauce is the SCNColorMask type introduced with iOS 11. If we apply a material to a geometry that has an empty colour mask set for its colorBufferWriteMask, the geometry will still write to the view’s depth buffer, masking other geometries, but won’t write any colours, allowing the underlying video stream to show through the scene. As an added bonus, any shadows cast over the occlusion geometry will still render, allowing virtual objects to throw shadows over real surfaces. For more on this technique, see the <a href="https://developer.apple.com/videos/play/wwdc2017/604?time=2721">WWDC 2017 session on integrating SceneKit and ARKit</a>.</p><p>We also need to ensure that the masking geometry gets drawn before the objects we want masked. The easiest way to do this is to give the occlusion nodes a negative renderingOrder.</p><p>We can use the ARPlaneGeometry object to update the ARSCNPlaneGeometry mesh by calling geometry.update(from: plane.geometry). We can continue to do this as ARKit gleans more information about the scene, dynamically updating our occlusion geometry. To do this we’ll use the renderer:didUpdateNode:forAnchor: method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/432cb10f06a40413358a893286862561/href">https://medium.com/media/432cb10f06a40413358a893286862561/href</a></iframe><p>One final piece of housekeeping. In my testing I found that when dynamically updating a geometry, SceneKit does not update the bounding volume for that geometry. This causes it to occasionally blink in and out of visibility, because it is mistakenly being clipped from the view frustum. We can fix this by manually setting the bounding volume of the node to be equal to the extent of the plane, whenever the geometry gets updated:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77f81740109bbc954bfc4b1e9231ee46/href">https://medium.com/media/77f81740109bbc954bfc4b1e9231ee46/href</a></iframe><p>For the full source code, please see <a href="https://github.com/Utsira/ARKitPlaneOcclusionDemo">this sample project</a>.</p><h4>Mapping the built environment</h4><p>Returning to our augmented office proof-of-concept, what are the results like? To visualise how the surface detection works we added an outline around each of the detected planes. The colour of the outline is derived from the normal of the surface. The exposed brickwork of TAB’s HQ in the Spitfire building is the perfect canvas. ARKit detects the blocking wall pretty quickly and masks the scene accordingly. We shouldn’t overhype the abilities of current technology. Without rear-facing depth sensors, current hardware is reliant on relatively well lit, textured surfaces, and surface-detection is currently limited to planes that are parallel or perpendicular to the ground. For the foreseeable future, users are generally going to want to prevent real world objects from obstructing their view of AR scenes. But the potential here for building an intelligent awareness of the built space surrounding the user, and then richly augmenting that space, is already clear.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f65c1f50b67a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kinandcartacreated/augmenting-the-workplace-with-arkit-f65c1f50b67a">Augmenting the workplace with ARKit</a> was originally published in <a href="https://medium.com/kinandcartacreated">Kin + Carta Created</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>