<?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 Geordie J on Medium]]></title>
        <description><![CDATA[Stories by Geordie J on Medium]]></description>
        <link>https://medium.com/@ephemer?source=rss-6db97eff6e29------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XN6taBH-Js7X4UfFqP52eg.jpeg</url>
            <title>Stories by Geordie J on Medium</title>
            <link>https://medium.com/@ephemer?source=rss-6db97eff6e29------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 10:54:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ephemer/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[Using JNI in Swift to put an app into the Android Play Store]]></title>
            <link>https://medium.com/@ephemer/using-jni-in-swift-to-put-an-app-into-the-android-play-store-732e542a99dd?source=rss-6db97eff6e29------2</link>
            <guid isPermaLink="false">https://medium.com/p/732e542a99dd</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[cross-platform]]></category>
            <dc:creator><![CDATA[Geordie J]]></dc:creator>
            <pubDate>Thu, 14 Jul 2016 20:38:29 GMT</pubDate>
            <atom:updated>2017-09-26T13:55:40.575Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is part three of what I’d planned to be a single-part series about putting what may have been the </em><a href="http://www.flowkey.com/"><em>first Android app</em></a><em> into the Google Play Store with a sizable Swift component. This is the </em><strong><em>most technical part</em></strong><em> so far and assumes some knowledge about Swift and Java programming.</em></p><p><em>Discover the reason why we went down this path in </em><a href="https://medium.com/@ephemer/why-we-put-an-app-in-the-android-play-store-using-swift-96ac87c88dfc#.93lznfg77"><em>part one</em></a><em>. For the steps we took to prepare our codebase and to get Swift code working in an Android .apk, see </em><a href="https://medium.com/@ephemer/how-we-put-an-app-in-the-android-play-store-using-swift-67bd99573e3c#.26kldolrm"><em>part two</em></a><em>.</em></p><p>So our Swift code worked in an <em>.apk</em> app bundle on Android devices. But the communication between the JavaScript code of our web app (running in a <a href="https://crosswalk-project.org/">Crosswalk</a> web view) and our Swift code was limited at best. No one on our four-person dev team had had much experience with Java, let alone the <a href="http://www.ibm.com/developerworks/java/tutorials/j-jni/j-jni.html">JNI (Java Native Interface)</a>, so there was another learning curve ahead of us…</p><p>Ignoring anything fancy like cross-language array or string manipulations, the first step was to get Java to call Swift at all and vice-versa.</p><h4>Calling from Java into Swift</h4><p>Since Swift compiles down to platform-native machine code that exists on the real Android ‘machine’ and not Java’s virtual machine, calling from Java into Swift is the easier case here. The following example takes some ints from Java, adds them together and returns the result back to Java directly.</p><blockquote>Java Code:</blockquote><pre>package <strong>com.flowkey.plugins</strong>; // also sets the namespace for JNI</pre><pre>// We use Cordova, but this works from any class (or activity)<br>public class <strong>OurSwiftPlugin</strong> extends CordovaPlugin {</pre><pre>    // Explicitly load all the required frameworks in order.<br>    // Android 5.0+ finds most dependencies by itself and<br>    // doesn&#39;t need as much hand-holding. We support 4.4+:<br>    static {<br>        System.loadLibrary(&quot;c++_shared&quot;);<br>        System.loadLibrary(&quot;scudata&quot;); // icu libs...<br>        System.loadLibrary(&quot;scuuc&quot;);   // see part 2 of this series<br>        System.loadLibrary(&quot;scui18n&quot;); // -------------------------<br>        System.loadLibrary(&quot;swiftCore&quot;);<br>        System.loadLibrary(&quot;swiftGlibc&quot;);<br>        System.loadLibrary(&quot;swiftJNI&quot;);</pre><pre>        // Contains the Swift code we want to call:<br>        System.loadLibrary(&quot;<strong>ourSwiftFramework</strong>&quot;);<br>    }</pre><pre>    private native int <strong>addInts</strong>(int <em>x</em>, int <em>y</em>);</pre><pre>    @Override<br>    public void pluginInitialize() {<br>        System.out.println(addInts(12, 22)); // prints 34<br>    }</pre><pre>}</pre><blockquote>Swift code (compiled into lib<strong>ourSwiftFramework</strong>.so):</blockquote><pre><a href="http://twitter.com/_silgen_name">@_silgen_name</a>(&quot;Java_<strong>com_flowkey_plugins</strong>_<strong>OurSwiftPlugin</strong>_<strong>addInts</strong>&quot;)<br><strong>public</strong> func callYourSwiftFunctionWhateverYouWantInternally(env: UnsafeMutablePointer&lt;JNIEnv&gt;, jobj: jobject, <em>x</em>: jint, <em>y</em>: jint) -&gt; jint {<br>    return x + y // jint is a typealias of Int32, so this just works<br>}</pre><p>This contrived and overly basic example should give you an idea of what is involved in calling Swift from Java. Some things to note:</p><ol><li>The Swift framework is actually called <em>lib</em><strong><em>ourSwiftFramework</em></strong><em>.so</em>, but it gets loaded via <em>System.loadLibrary(“</em><strong><em>ourSwiftFramework</em></strong><em>”)</em>. This isn’t specific to Swift (this is the standard way to load a dynamic library from Java) but it’s important to know.</li><li>We’re using an all but undocumented Swift feature ‘@_silgen_name’ to work around Swift’s <a href="https://en.wikipedia.org/wiki/Name_mangling">name mangling</a> and produce a symbol with a specific name that can be called directly by C or, in this case, Java.</li><li>The exported ‘@_silgen_name’ we’re providing from Swift must follow the JNI’s strict rules, namely ‘Java_[<strong>package_name</strong>]_[<strong>class_name</strong>]_[<strong>exported_function_name</strong>]’. I’ve highlighted the connections between these parts in the Java code.</li><li>The Swift function to be called must be top-level (not nested within a class or other structure) and <strong>public</strong>, otherwise it won’t appear in the global symbol table and JNI won’t find it!</li></ol><p>I should mention here that a function this trivial is absolutely a terrible use case for JNI. In the same way that accessing the DOM from JavaScript has a very high overhead, calling from Java into native code and vice-versa is <strong>not</strong> something you want to be doing over and over (like in a loop).</p><p>In general, stick to one side of the Java-Native bridge for as long as you can and put meaningful boundaries between where Java ends and native begins: it’s better to send a bunch of data at once, do some significant amount of processing on it and then send it back across the bridge, rather than constantly switching back and forth.</p><p>In our case, we access the microphone buffers in real-time using <a href="https://developer.android.com/ndk/guides/audio/opensl-for-android.html"><em>OpenSL ES</em></a> from C, send these buffers to Swift about 50 times per second (remembering that native-native is basically free), then if (and only if) we find something interesting in the microphone data (i.e. the user has played the right notes), we send a callback back across the bridge into Java. Which leads us to the next challenge.</p><h4>Calling from Swift into Java</h4><p>Now we’re into the fun stuff. Not that I’ve ever done it before myself, but I gather that writing JNI code in <em>C</em> (being a supported language for <a href="https://developer.android.com/ndk/index.html">Android Native Development Kit or NDK</a>) is painful enough to begin with. But at least <em>C</em> has some form of code completion and half-decent debugging support on Android. Swift doesn’t really have either of those things, although the code completion on Linux platforms is <a href="http://nosubstance.me/post/swift-code-completion-for-vim-on-linux/">generally</a> <a href="https://github.com/terhechte/SourceKittenDaemon">improving</a>, and some of the NDK debugging tools also work with Swift out of the box to some degree.</p><p>To write JNI in Swift though, stabbing in the dark and imitating JNI examples written in <em>C(++), </em>hoping the code would compile in Swift, is clearly not enough. So I moved the development of the parts of our code interacting with the JNI from our Linux development server back into Xcode, which is pretty easy to do:</p><ol><li>Start a new Xcode project, as blank as you can get it. I used the macOS command-line tool template. Choose Swift as your project’s language.</li><li>Add a (dummy) <em>Objective C</em> file to the project and say yes to adding a Bridging Header.</li><li>Drag the <em>jni.h</em> header from your Android NDK installation at <em>ndk_root/platforms/android-24/arch-arm/usr/include/jni.h </em>into your Xcode project, choosing to <strong>copy the file</strong> if needed. Download the NDK <a href="https://developer.android.com/ndk/downloads/index.html">here</a>.</li><li>Remove the numerous references to <em>__NDK_FPABI__ </em>within the Xcode copy of <em>jni.h</em> (Xcode won’t understand the Android-specific macro and will fail to load the header) and import it into the Bridging Header created for you in step 2 — just add the line <strong><em>#import “jni.h”</em></strong></li></ol><p>And now you have an Xcode project with code completion for the Android JNI!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*A38D65XtUMGIvhfpJt6exg@2x.png" /><figcaption>Code completion is one of those things you don’t miss until its gone.</figcaption></figure><p>From here it was <em>relatively</em> easy to put the required pieces together to call from Swift into Java. I say relatively easy, because this is still some pretty heavy stuff — the JVM can be a difficult beast to deal with from the outside, and Swift’s memory-safety guarantees make it explicitly difficult to work with unsafe types like the raw pointers (and pointers to pointers) rife throughout the JNI’s API. But we’d gotten so far already, it only made sense to finish the job. Plus, things were just starting to get fun!</p><p>Before we get too carried away though, let’s use our new knowledge and JNI-enabled Xcode project to call a Java method from Swift.</p><p>The following simple example will give you an idea of how Swift and Java can interact. The Java code pushes some numbers into an Array in Swift. When the Swift Array has five elements in it, it will run a callback back into Java with the result.</p><blockquote>Java Code:</blockquote><pre>package <strong>com.flowkey.plugins</strong>; // see first example, above</pre><pre>public class <strong>OurSwiftPlugin</strong> extends CordovaPlugin {<br>    static {<br>        // ... and the other dependencies here (see example above)<br>        System.loadLibrary(&quot;<strong>ourSwiftFramework</strong>&quot;);<br>    }</pre><pre>    private native void <strong>pushIntOntoSwiftArray</strong>(int <em>n</em>);</pre><pre>    @Override<br>    public void pluginInitialize() {<br>        pushIntOntoSwiftArray(2);<br>        pushIntOntoSwiftArray(5);<br>        pushIntOntoSwiftArray(7);<br>        pushIntOntoSwiftArray(12);<br>        pushIntOntoSwiftArray(8);<br>    }</pre><pre>    // Swift will call this when its array contains five elements<br>    private void <strong>onArrayFull</strong>(int arraySum) {<br>        System.out.println(arraySum); // prints 34<br>    }</pre><pre>}</pre><blockquote>Swift code (compiled into lib<strong>ourSwiftFramework</strong>.so):</blockquote><pre>var intArray: [jint] = []</pre><pre><a href="http://twitter.com/_silgen_name">@_silgen_name</a>(&quot;Java_<strong>com_flowkey_plugins</strong>_<strong>OurSwiftPlugin</strong>_<strong>pushIntOntoSwiftArray</strong>&quot;)<br>public func pushInt(env: UnsafeMutablePointer&lt;JNIEnv&gt;, jobj: jobject, n: jint) {<br>    <br>    intArray.append(n)<br>    <br>    if intArray.count &gt;= 5 {<br>        let callbackResult = intArray.reduce(jint(0), combine: +)<br>        callOnArrayFull(env, jobj: jobj, value: callbackResult)<br>        intArray.removeAll()<br>    }<br>}</pre><pre>private func callOnArrayFull(env: UnsafeMutablePointer&lt;JNIEnv&gt;, jobj: jobject, value: jint) {<br>    let jni = env.memory.memory // env is a pointer to a pointer!<br>    <br>    let methodName = &quot;<strong>onArrayFull</strong>&quot;<br>    let methodSignature = &quot;(I)V&quot; // one <strong>I</strong>nt argument, returns <strong>V</strong>oid</pre><pre>    let javaClass = jni.GetObjectClass(env, jobj)<br>    let methodID = jni.GetMethodID(env, javaClass, methodName, methodSignature)<br>    <br>    let valueAsJValue = jvalue(i: value)<br>    var methodArgs: [jvalue] = [valueAsJValue]<br>    jni.CallVoidMethodA(env, jobj, methodID, &amp;methodArgs)<br>}</pre><p>Are you still with me? Now, my goal isn’t to teach you how to use the JNI; there are much better resources for that on the web. What I’d like to do though is go over the Swift-specific parts, namely when <em>intArray.count &gt;= 5</em> and we run <em>callOnArrayFull</em> in Swift:</p><ol><li>The <em>env </em>argument passed in by Java is a <strong>pointer</strong> to the <em>JNIEnv</em> type, defined in <em>jni.h</em>. <em>JNIEnv</em> <strong>is itself a pointer</strong> to the JNI-internal <em>JNINativeInterface</em> type, which encapsulates almost all JNI functionality. To access it, we need to tap into <em>env.memory.memory</em> (<em>env.pointee.pointee</em> in Swift 3+) — this sure gets tiresome and ugly if you’re doing it a lot.</li><li>We have to pass <em>env</em> as the first argument into any call to a <em>JNINativeInterface</em> method. This is the legacy of <em>C</em>.</li><li><em>GetObjectClass</em> and <em>GetMethodID</em> work just as they do from C. Note, it’s critical to provide the correct method signature of the Java method you’re trying to call (see <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/types.html">Oracle’s JNI Docs</a> for more info).</li><li>When calling a Java method from native, the calling arguments must all be wrapped in <em>jvalue</em> structs. Autocomplete is invaluable here to figure out what all the cryptic abbreviations mean when creating a <em>jvalue</em> instance.</li><li>The most Swift-compatible way of calling a Java method is to use <em>Call(ReturnType)MethodA</em>. This method allows you to pass an Array of <em>jvalue</em> arguments to Java (the array can be empty or contain just one <em>jvalue</em> argument). Collecting these arguments in a mutable Array to be referenced with the <em>&amp;</em> character avoids dealing with any icky <em>UnsafeMutablePointer</em>s as much a possible.</li></ol><p>As you can see, even calling a simple Java method from Swift is quite involved and potentially error-prone, especially when you compare it to calling <em>C&lt;-&gt;Swift</em> or even <em>Java-&gt;Swift.</em></p><p>To deal with that, I started abstracting away much of this complexity in the WIP <a href="https://github.com/SwiftAndroid/swift-jni">SwiftJNI module</a> I started on the SwiftAndroid GitHub. SwiftJNI imports and exposes <em>jni.h</em> (internally as CJNI), but it also implements a Swift class called <em>JNI</em> that more closely resembles the slightly nicer C++ API, removing the need for dancing around with <em>env.memory.memory. </em>It also internally checks for null pointers at key points and returns optionals where appropriate for more Swift-like coding<em>.</em></p><p>The module also contains the beginnings of an even Swiftier subclass of <em>JNI </em>called <em>SwiftJNI</em>, which is incomplete and very experimental for now. There are also functions for converting between Swift Arrays and Java arrays in both directions, and, important for the use case above in particular, the <a href="https://github.com/SwiftAndroid/swift-jni/blob/master/SwiftJNI.swift#L139-L215">JavaCallback struct</a>. These abstractions also let you call JNI methods from outside the context (i.e. function call) they were created in, and go some way to deal with concerns about threading.</p><p>I think this article is long enough for now, and I haven’t had time to work on SwiftJNI lately(it meets our needs and then some for now) but if there is enough interest I will consider writing more about the module in the future. It is also worth noting that, due to recent advancements in Swift (namely <a href="https://developer.apple.com/videos/play/wwdc2016/403/?time=1739">CF_SWIFT_NAME</a>) the manual wrapping I did may even be unnecessary now.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=732e542a99dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How we put an app in the Android Play Store using Swift]]></title>
            <link>https://medium.com/@ephemer/how-we-put-an-app-in-the-android-play-store-using-swift-67bd99573e3c?source=rss-6db97eff6e29------2</link>
            <guid isPermaLink="false">https://medium.com/p/67bd99573e3c</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Geordie J]]></dc:creator>
            <pubDate>Fri, 08 Jul 2016 19:25:18 GMT</pubDate>
            <atom:updated>2017-09-25T17:05:57.025Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is the second (more technical) part of our story about putting what was possibly the first app on the Play Store with a significant Swift component. </em><a href="https://medium.com/@ephemer/why-we-put-an-app-in-the-android-play-store-using-swift-96ac87c88dfc#.fgnftxjri"><em>See here</em></a><em> for part one.</em></p><p>As I described in the <a href="https://medium.com/@ephemer/why-we-put-an-app-in-the-android-play-store-using-swift-96ac87c88dfc#.fgnftxjri">first part</a> of this series, we had time and business pressure to release a <a href="http://www.flowkey.com/">flowkey</a> Android app, with no proven technology path to achieve it. In summary, we decided to take our chances that Swift would become available to us on Android to run our performance-critical Pitch Detection code once Swift went open source (at a then-unknown point in time) <em>without </em>having to rewrite that code in <em>C(++)</em>. This would accompany our hybrid largely HTML5-based app which had already proven itself performant and compatible running on Android up until then.</p><h3>Preparing our Swift Code</h3><p>In a way we were banking on a miracle, but as with all miracles that turn out for the best we had reason on our side: we had a good idea the plan was realistic due to insights learned from Romain Goyet’s <a href="http://romain.goyet.com/articles/running_swift_code_on_android/">post</a> about how LLVM works (including a basic, but working example on Android). The timeframe also seemed doable thanks to Apple’s suggestion that Swift would be open sourced by the end of 2015. So we took the dive.</p><p>And the good news came quickly: within a week of deciding to give Swift a try on Android, <a href="http://www.swift.org/">swift.org</a> went live along with Apple’s corresponding open source GitHub repository. Support for Linux was not 100% complete but for practical purposes ready ‘out of the box’. Although we still couldn’t compile Swift to Android immediately (which is a Linux system at its core), we very quickly got a good idea of what would be available to us in Swift and what wouldn’t. The biggest hurdles we saw would be in two areas:</p><ol><li>The Foundation framework: Math functions</li><li>The Accelerate framework: Audio Filtering</li></ol><h4>Foundation-specific Math</h4><p>We didn’t expect Foundation to be available to us from the start (actually we assumed it wouldn’t be available at all). We also wanted to avoid dancing around with conditional import statements at the top of every source file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*Ii6zU79fMDnQeTSN8X-FFQ@2x.png" /><figcaption>Something we didn’t want to deal with in Every Damned File, let alone the API differences</figcaption></figure><p>Instead, we decided to promote code readability and maintainability in our codebase (perhaps at the cost of potential bugs) by setting up a level of indirection. We made one file for each platform that would import the functions we needed and provide them at a Framework-internal access level to the rest of our code. So we’d compile <em>FlowMath.swift</em> for Darwin targets like iOS — importing <em>Foundation</em>; and <em>FlowMathAndroid.swift</em> for Android — here importing <em>Glibc</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*-Wyyz3yWObsDKbTUg2l0tA@2x.png" /></figure><p>We also wanted to be able to just write, for example, <em>sin(x)</em> for both <em>Float</em> and <em>Double</em> types, regardless of platform. This worked in <em>Foundation</em> but not in <em>Glibc </em>(which is a C library, and by definition unaware of Swift’s function overloading). So writing our own wrapper here also meant for the most part we didn’t have to change the rest of our codebase at all. We also wrote our own versions of some higher-order functions like <em>mean() </em>and <em>median()</em> of floating point arrays, which had used some Apple-optimised functions on iOS.</p><p>Overall, this allowed us to share much more code between Android and iOS than we could have otherwise, and kept the implementation details clearly encapsulated in one place.</p><h4>Audio Filtering</h4><p>One of the most important aspects of what we were doing in our native Swift code was filtering audio (essentially EQing, for the not-so-audio-minded among us). We had been using a library called <a href="https://github.com/bartolsthoorn/NVDSP">NVDSP</a> for this purpose, which internally made use of a relatively obscure function in Apple’s Accelerate framework to run a recursive filter, <em>vDSP_deq22():</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*oqhIa_1BYolDc0lM9_w6xQ.png" /><figcaption>What vDSP_deq22() actually does</figcaption></figure><p>From what I understood, the author of NVDSP, Bart Olsthoorn, had used a Google-translated version of a Japanese blog to understand how to use the function. The library had served us well up until then, but the thought was not exactly encouraging when we needed a deep enough understanding to implement the function ourselves by hand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*Xu3IQJe9F3rGCQrlWa0S4A.gif" /><figcaption>Swift’s safety guarantees do not protect against programmer error</figcaption></figure><p>Luckily, Apple’s documentation does in fact reveal exactly what the function does beneath the surface (consult the friendly formula above). <a href="http://stackoverflow.com/questions/34312682/reimplement-vdsp-deq22-for-biquad-iir-filter-by-hand">After some experimentation and frustration</a> we were eventually able to write our own version of the filter function that produced the same output given a certain input (the necessary performance optimisations came much later of course).</p><h3>Trying it out</h3><p>So, we had a code base that would theoretically run on Android, but no compiler to generate the binary and no standard library to link it with. This was a major issue. Our entire four-person development team at flowkey has its roots firmly in web development meaning Swift itself was a learning curve, let alone compiler hacking and porting. I tried poking around in the Swift source code, but tackling the problem alone of trying to get the Swift standard library to compile for a new platform was one that I was ultimately entirely unqualified for.</p><p>Thankfully, an unassuming hacker and quiet hero by the name of <a href="https://github.com/zhuowei">Zhuowei Zhang</a> (@zhuowei on GitHub) had also <a href="https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151207/000171.html">started to make progress</a> and <a href="https://github.com/SwiftAndroid/swift/commit/7c502b6344a240c8e06c5e48e5ab6fa32c887ab3">share it with the world</a> (this is a squashed commit of the final outcome). I quickly expressed interest in the endeavour and began ‘helping’ wherever I could. To begin with, that involved little more than testing the latest progress @zhuowei had made on the <a href="https://github.com/SwiftAndroid">SwiftAndroid</a> repository, and reporting on how it worked with real code (@zhuowei had only limited experience with Swift at the time). In that way, it took only a few weeks to get all of Swift’s features working on an Android device.</p><p>But the work was far from over. Having access to a reliable compiler and a fully-fledged Swift standard library to make binaries for the Android command line was as exciting as it was promising, but it still left a fair bit to be desired in the bigger picture of Android’s Java-based ecosystem. What we needed was a user-compiled Swift shared library running on a non-rooted device from within a standard <em>.apk</em> application bundle.</p><h4>The problem of Swift’s own dependencies</h4><p>Up until that point, all the testing we had done was in the terminal of either a rooted device or an Android emulator. The reason being that Swift binaries would only run if the <em>LD_LIBRARY_PATH </em>environment variable was set to help locate Swift’s dependencies — its standard library, <a href="http://site.icu-project.org/"><em>libicu</em></a> and so on.</p><p>As we soon found out, the Android linker ignores <em>LD_LIBRARY_PATH</em> when loading libraries from within Java via <em>System.loadLibrary()</em>. Instead, it looks in its own system directories, and within the <em>.apk</em> bundle itself. The problem was, this didn’t work. Android’s error message was entirely unhelpful here too (unfortunately a recurring trend in our growing experience), stating that our Pitch Detection library was simply ‘not found’. Moving up the dependency chain and specifically loading various <em>libicu </em>libraries resulted in a message saying that <a href="https://github.com/SwiftAndroid/swift/issues/7">these were ‘not found’ either</a>. The catch was that certain libraries <strong>did </strong>load using this exact method, so we knew something was up.</p><p>After some trial and error and using some command line tools I’d never heard of before, we discovered that the load order of Android’s dependencies was important: it looked in its own directories <strong>first</strong>, before looking within the application bundle. It seemed Android was loading its own outdated version of <em>libicu</em> (which was missing the code Swift depends upon) and ignoring the version we were bundling in the <em>.apk</em> (I’m sure this was well intentioned, but seriously: why, Android, why??)</p><p>We tried to work around this for weeks, trying different solutions (parallel to testing Swift itself) and asking fruitless <a href="http://stackoverflow.com/questions/34441104/android-ndk-resolve-dynamic-library-version-conflict">StackOverflow</a> <a href="http://stackoverflow.com/questions/34420689/android-swift-jni-unsatisfiedlinkerror-system-loadlibrary-looking-in-the-wrong-p">questions</a> with no progress at all. In the end, the day after the Christmas weekend, we stumbled across a strange workaround in an obscure Google Groups <a href="https://groups.google.com/forum/#!msg/android-ndk/_UhNpRJlA1k/7_R6NwhiKa0J">post from 2011</a>: rename the dependency files and use a text find-and-replace <strong>within the binaries themselves</strong> to update the dependency they were looking for. This would remove the version conflict with Android’s own version of <em>libicu</em> and allow us to load our own. The only catch was that, being binaries, we had to keep the strings we changed the same length. So <em>lib</em><strong><em>i</em></strong><em>cu</em> ended up being called <em>lib</em><strong><em>s</em></strong><em>cu</em> (s for Swift). So we ran</p><blockquote>rpl -R -e libicu libscu libswift*.so</blockquote><p>and ended up with what we needed– finally we could load Swift libraries on Android!</p><h4>Testing our Pitch Detection library</h4><p>By this point I was very happy to be all but out of the zone of compilers and binary tools and more into my comfort zone of working with Swift! And thanks to the prep work we’d done cleaning up our codebase for cross-platform use, it didn’t take long at all to get the first results.</p><p>Within 24 hours (albeit at about 4am from memory, note the <em>f.lux</em> warm display tint) we had an <em>.apk</em> running on a normal device, including a basic solution to the next challenge: making calls from Java into Swift and vice-versa.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F173947051&amp;url=https%3A%2F%2Fvimeo.com%2F173947051&amp;image=http%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F580548475_640.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=vimeo" width="640" height="360" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f19414e2e5ffc0f013ae6193aca7c46/href">https://medium.com/media/9f19414e2e5ffc0f013ae6193aca7c46/href</a></iframe><p>My colleague <a href="https://github.com/rikner">Erik</a> had already played around with some <em>C(++)</em> audio code on Android and had some callbacks to Java working via the <a href="https://en.wikipedia.org/wiki/Java_Native_Interface">JNI</a>, so in theory it was just a case of calling the C JNI library from Swift code. To achieve this I initially just hacked the JNI headers into Glibc’s <em>module.map</em> as an add-on to the Android Swift Standard Library (I eventually cleaned this up and made a separate JNI module; see the next part of this series). This allowed us to call a Java method with no arguments (and no data), as seen above.</p><p>We needed a bit more control though: to truly interface with our web app (not forgetting the goal of releasing <a href="http://www.flowkey.com/">flowkey</a> for Android!) we still had to use the JNI to pass around some strings and arrays to and from Java. The fact that I’d never used JNI before (or Java in any significant manner, for that matter) didn’t help. Neither did coding Swift in vim on a remote linux virtual machine — Swift for Android still today only compiles from a Linux host (nowadays we’re using <a href="https://www.vagrantup.com/">vagrant</a>). With no code completion, no debugger and Android’s inaccurate error messages, the next stage proved more challenging than I’d expected.</p><p>See <a href="https://medium.com/@ephemer/using-jni-in-swift-to-put-an-app-into-the-android-play-store-732e542a99dd">here</a> for the third part in the series: a technical introduction to calling Swift from Java and vice versa using the JNI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67bd99573e3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why we put an app in the Android Play Store using Swift]]></title>
            <link>https://medium.com/@ephemer/why-we-put-an-app-in-the-android-play-store-using-swift-96ac87c88dfc?source=rss-6db97eff6e29------2</link>
            <guid isPermaLink="false">https://medium.com/p/96ac87c88dfc</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Geordie J]]></dc:creator>
            <pubDate>Thu, 07 Jul 2016 11:22:37 GMT</pubDate>
            <atom:updated>2016-07-08T19:26:52.445Z</atom:updated>
            <content:encoded><![CDATA[<p>Towards the end of 2015 we were faced with a dilemma. No sooner had we released the <a href="http://www.flowkey.com/">flowkey</a> iPad app than the requests started streaming in for an Android version. “Don’t you know that Android has the majority market share?” “You do know that iPads are for mindless hipsters, right?” “Don’t you love us anymore??” “Pleeease??”</p><p>The message was clear, but the problem was large: With Android’s large market share comes a host of issues that iOS development simply doesn’t have to deal with: different screen resolutions, widely varying performance characteristics even on new high-end devices, even fundamentally different processor architectures on same-generation devices. As a small development team (there were four of us at time of writing), the prospect of making an Android app on an unfamiliar stack to try to cover all of those bases in any reasonable amount of time, all the while developing, debugging and improving the browser and iPad versions could have seemed impossible.</p><p>What we did have however were the blessings of good fortune in the form of our CTO’s early decision to go hybrid (via Meteor), and of good preparation via the huge efforts we put into optimising performance for the iPad version to make it run smoothly even on a prehistoric (in computer years) <a href="https://en.wikipedia.org/wiki/IPad_2">iPad 2</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pN_jMLH9j-vYWAINo9ieYg.png" /></figure><p>The core feature of flowkey is what we simply call “the player”. You can watch and listen to the song or excerpt you are trying to learn, slow it down, make loops and – importantly – learn in “wait mode”.</p><p>Wait Mode gives you as a learner the opportunity to get comfortable with finding the notes in a song at your own pace. The video and sheet music play up until a note or chord, then pause and wait for you to play the right notes on your real piano or keyboard before continuing again to the next note or chord.</p><p>In the browser, the pitch detection works via JavaScript’s <em>Web Audio API</em>, including <em>getUserMedia()</em> to access the device’s microphone. But this is where the hybrid dream starts to fall apart: the iPad’s browser, Safari, and its programmatic counterparts <em>UIWebView</em> and <em>WKWebView</em> <strong>do</strong> have an implementation of the <em>Web Audio API</em>, but <strong>not</strong> of <em>getUserMedia()</em>. This restriction makes it impossible to access the microphone from the browser context, and puts one of our core features out of reach for hybrid use.</p><p>At first we tried to get around this by using native code to inject microphone audio buffers into the WebView for processing in our existing JavaScript code. It worked, but only barely — there was a significant lag and it had a noticeable performance impact even on the latest model iPad Air. Not wanting to settle for a second-rate experience, we made a decision that would directly affect the future for our Android app as well: we decided to rewrite our pitch detection routines in Swift.</p><p><a href="http://www.swift.org/">Swift</a> is an absolute pleasure to use. Using Swift, it is fun to write concise, beautiful and performant code that reads well, is easy to reason about and easy to debug. Two years after starting with Swift I still very much have the same sentiment about it as the one expressed by <a href="https://medium.com/u/3334a58db4c1">Dan Kim</a> about Kotlin <a href="https://m.signalvnoise.com/how-i-fell-in-love-with-a-programming-language-8933d5e749ed#.qplm76ton">here</a>.</p><p>The Swift version of our pitch detection worked. It was extremely performant and provided a way better experience than the <em>Web Audio API</em> ever could have, with significantly less latency and higher accuracy. And there was much rejoicing.</p><p>Which left us a few months later with our dilemma: we had a hybrid app that already worked pretty well on Android, but one of our core features was missing (actually two – a story for another time) due to performance reasons. We had a JavaScript version of the pitch detection and a Swift version, but neither of those were suitable for our increasingly urgent Android project.</p><p>So we had to make a choice: use JavaScript and restrict downloads of Android app to only the newest devices, and still suffer a performance impact when using the pitch detection? Rewrite the pitch detection once again in <em>C</em> or <em>C++</em>? Give up on the feature all together on Android?</p><p>The only one of those potential paths we seriously considered in the end was rewriting the pitch detection again in a more portable language like C. Yes, this would have been possible, but would have likely taken quite some time again and, considering none of us on the team had any significant experience with either of those languages, would have likely been riddled with bugs and inconsistencies. As a four-person team, we also didn’t want to maintain three versions of the essentially the same code.</p><p>A glimmer of light came in the form of Romain Goyet’s <a href="http://romain.goyet.com/articles/running_swift_code_on_android/">blog post about running Swift code on Android</a>. Based on his observations, it appeared possible — especially once Swift went open source at a then-unknown point in time — to run Swift code via the <a href="https://en.wikipedia.org/wiki/Java_Native_Interface">JNI</a> from Java on Android devices. After some deliberation (and considering time wasn’t on our side), we decided to take the risk and go down the path of getting our Swift code running on Android.</p><p>See the next part for <a href="https://medium.com/@ephemer/how-we-put-an-app-in-the-android-play-store-using-swift-67bd99573e3c#.g9mtoogan"><strong><em>How </em>we put an app in the Android Play Store using Swift</strong>.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96ac87c88dfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>