October 20, 2014

Uploading a file with SWIFT via POST multipart/form-data

Imagine a scenario where you’ve got a PHP based API of some sort. Imagine that one of the endpoints of the API allows you to upload a file (JSON file, image, CSV file, etc…) for further background processing. Then imagine that on the PHP side, the uploaded file’s details are being obtained by using the PHP superglobal $_FILES. Finally, imagine that you’re building a SWIFT-based library (or more correctly module) or app that uses the aforementioned API endpoint.

This is what I was faced with for a while and have been trying to find a solution to. Obviously, one of the things I jumped into when I started this project was to use Alamofire. Alamofire is perfect for getting down to business and not spending time coding all the nitty-gritty one has to deal with when working with APIs. It even offers an Upload method (Alamofire.upload(_, _, _)) which works pretty well, except gets a little complex when needing to perform the type of operation I needed it for.

So I ended up with two solutions. The first one using the straight up networking API offered by SWIFT and once I got that working, I built up the second solution which works with Alamofire. In this post, I will briefly show how I went about both of them.

First, here’s the basic, unassuming and straight-to-the point PHP endpoint we were discussing earlier. Note that this has been greatly simplified for the purpose of this blog post:

testupload.php

POST multipart/form-data file upload with SWIFT networking API

Uploading a file via multipart/form-data means one has to keep in mind a couple of things:

  • A data boundary has to be set: the data boundary is a piece of random string that should not in any occasion whatsoever re-appear within the data being sent to the server as server uses it to figure out where individual data sets begin and end.
  • A Content-Type such as “multipart/form-data; boundary=BoundaryStringGoesHere” has to be set as well.
  • In the HTTP Body of the request, a Content-Disposition as well as mime type of the file being uploaded need to be set as well.

In the code below, I define the data boundary as a constant string that I set but really, the best would be to have this being randomly generated by a function you define somewhere. In UploadNative(), we create a function that uploads a file which path’s has been provided:

UploadController.swift

Running the code below will easily upload the contents the specified file to the http://testapi.example.com/testupload.php endpoint. I ended up going the “native” way because I could not figure out how to do this with Alamofire. Here’s a quick code snippet (more like an XCTest really) which shows how one could use the UploadNative(_, _) method:

UploadControllerTests.swift

POST multipart/form-data file upload with Alamofire library

Right, the principles discussed earlier apply here as well. And I am being a lazy blogger. But the point is to show that this is equally doable with Alamofire, should one desire to do so. There seldom is documentation on this around the Web, which again makes it rather important to share with you guys. When working with Alamofire, I prefer working with routers; and the reason for doing so will not be directly apparent in the current post. However, in the very near future, I shall spend more time detailing the reasons behind such preference. In the meantime however, let’s march on. We will start by creating a router as follows:

Router.swift

As you can see, the bulk of the work in creating the request is done in the Router. If one pays attention, one realizes that whereas previously we were concatenating strings, here we are directly working with instances of NSMutableData or NSData. This is to demonstrate that it is possible to do it both ways and I am quite confident that going the NSData.appendData() way would be the most recommended, mostly when dealing with pieces of data that need to be uploaded and that are not the text mime type.

We will now proceed to use our Alamofire-based router to perform a file upload. For this, we have added an UploadWithAlamofire(_, _, _) method which looks as follows:

UploadController.swift with UploadWithAlamofire method

As it can be seen, the code is much more succinct and to the point and it works! It really took me a while to figure this out. Using Alamofire.upload() simply did not work for this kind of situation. Let’s add some code to our previous XCTestCase to show how our brand new Alamofire-based method can be used:

UploadControllerTests.swift with UploadWithAlamofire test

And voila! We’re done! It is important to note that I am pretty new at coding using SWIFT and that the provided code may not be perfect. More can and should be done. For example, the boundaries should be auto-generated. The file that is being uploaded mime type should be obtained programmatically and a few other things. However, the objective of this post was not to dive into it all but to quickly show how to create multipart/form-data file uploads in SWIFT.

All code used in this post can be found here.

PS: Updated the code to be compliant with the changes from Xcode 6.1.

October 6, 2014

Submitting proposals for a conference - back to noob status

There was a time in my life when submitting papers to and for conferences was something I did quite often. I was much younger, had more time on my hands and a bursting amount of creativity (there we go again with the whole rekindling my creativity thing.

So recently, on my side of the world, there was a tech conference I really wanted to go to but regrettably could not make it. I was however reminded that it had been years since I’ve put in anything, whether it be going to conference, be a speaker there or just submitting papers and going through the anticipation of whether my paper made it through or not. I have to admit, it seemed things had gotten stale all this time I was focusing on just one thing: do my job and do it pretty darn well.

So I found myself a conference I am very much interested in. I probably should look at a couple of others. As they say, don’t put all your eggs into one basket. However, I also needed to keep in mind that I haven’t done this in a very long time. Once I am certain of what my interest is, I probably at some point would publish the link to said-conference. In the meantime, looking at what was required to submit a proposal, I was faced with an interesting set of problems:

  • The conference requires submission of at least 3 proposals. This allows them to try really hard to get you in.
  • The topics have to be very specific and yet broad enough to build up interest. After all, one does want enough people to attend one’s workshop / speech yes?
  • One needs to know the chosen / selected / proposed topic in detail: this one is quite interesting because I’ve got broad knowledge of the things I do as well as really detailed knowledge. But the question remain, how do I take a whole bunch of code, remove any specificities and present it to a bunch of people in order to augment their knowledge.
  • And finally, oh yes finally, there is always that thing in your mind that keeps saying: surely, if I know all this stuff, why wouldn’t the rest of the world (here conference participants) know it as well. Would they find it too easy (and maybe it shouldn’t be a conference topic), not advanced enough (am I wasting their time) and so on and so forth. But I reckon, we’re getting ahead of ourselves here.

The point is, getting back to blogging and trying to figure out interesting topics for this conference would probably push me to go through that creativity rebirth I’ve been dying for.

I’d be really interested in what others out there do. Have you had to submit a set of topics as proposals for a conference in your industry? How did you go about it? How did you get to select topics that weren’t too academic in nature, were interesting and pretty good enough to get through the sea of competitive proposals that the conference committee is certain to receive?

October 4, 2014

An attempt at rekindling my creativity

So, my last post on this blog was in July 2010. My word… How has the world profoundly changed since then. My personal life has changed quite a bit as well. I had experiences that now define me, I grew up quite a bit, changed my mind about a few things, learned more and on the other hand, still struggling to come to terms with what life is all about in general.

I’ve gained a lot along the way (here we are, 4 years later. How incredible!). I’ve lost somethings too. Recently, I got reminded of one of those things I’ve lost: being incredibly creative. I am still as creative as I used to be when it comes to my work. But that is not the kind of creativity I am referring to here. I am referring to the kind of creativity that would make me push boundaries, come up with innovative ideas but not just let them sit somewhere in the recesses of my mind. But rather, bring them into reality, learn along the way and then use what I learned during the process in my everyday life. More than that, get a chance to share those lessons with others through my writing. One of the reasons this may have happened would be fear. Fear of starting something and not finishing it. From not finishing it, fear of not feeling accomplished. It really is interesting to age. I seemed to get more scared of failures than just deciding to do things for the fun of it.

Today and the past few days I’ve been thinking of rekindling my creativity. But how would I be able to do this? It’s been so long. I then remembered that one of the things that got me to be creative was the process of sharing it with the world via my blog. It was with surprise that I found out that my blog still ran, after all these years. It felt amazing browsing through my previous articles and recognize the person who wrote them. I thought, what best way of bringing that creativity back other than restarting to write again. The blog was still there and I have access to better tools, better connectivity than I did back then. And I believe I’ve got a lot to share and learn along the way.

So I looked around, got myself a copy of ByWord as it would allow me to write without worrying or being distracted about clunky Blogger Web UI and post from within.

I guess this post is also a way of public accountability. When you write things down, mostly when you communicate things by writing, you’re held to your words by the potential readers. You know you’ve got to push through. And by doing so, you get to become better and more creative at the things you do.

I am quite glad to be back and I am looking forward to post stuff regularly again. The only difference going forward is that I probably would post about more than just technology, code and related topics. There is too much happening in life to constrain one-self to a specific set of topics. I am excited by this prospect to be honest. And I can’t wait to get started! :-)

May this be the beginning of many great things.

July 19, 2010

Default function formal parameters in Javascript

Having been programming quite a bit in Ruby and PHP lately, I have gotten used to default formal parameters. This is when you can call a function and omit some of the parameters, the function then assigns pre-defined default values when evaluating those parameters.

It's quite handy at times and helps keep the code succinct and clean.

To see what I mean, in ruby for example you would do the following:

  def a_function(a_param = default_value)
    ...
  end

Later on, the function above could be called in any of the following ways:
  # call function with default param values
  a_function()

  # or specifying a value for the param
  a_function("foo")

In order to achieve the same in Javascript the following is recommended:
  def a_js_function(a_param) {
    var a_param = a_param || default_value;
  }

With the above, you can now call your Javascript function in any of the following ways depending on what you're looking at achieving:

  // call function with default param values
  a_js_function();

  // specify a value for that parameter
  a_js_function("foo");

Note that you can apply the above to all the required parameters of your Javascript function.

That's it!

June 23, 2010

Solving it: iOS 4.0 installation stalls on iPhone 3G issue

I did a successful upgrade to iOS 4.0 last night on my iPhone 3G although I started it a day earlier. If anyone turns out to have an issue where their updates gets stuck at about 60% or 90% no matter how many times they restart it, or how long they wait, the solution is as follows:

depending on the computer operating system of the user, they should open one of the following folders:

  • Mac OS: ~/Library/Application Support/MobileSync/Backup
  • Windows XP: %AppData%\Apple Computer\MobileSync\Backup
  • Windows Vista: %AppData%\Roaming\Apple Computer\MobileSync\Backup
  • Windows 7: %AppData%\Roaming\Apple Computer\MobileSync\Backup

Then move the backup folder inside it to their desktop (move, not copy it).
The next step is to restart the restore process for with the iOS 4.0 ipsw. It will go through seamlessly.

Once it's done as iTunes and the phone will let them know, they should unplug it from iTunes and unplug the USB cable from their PC / Mac

Next, they should move the backup folder that was inside the directory above back to its original location. Replug the iPhone and it will restore their data from iPhone OS 3.y.x.

Hope this helps as it took me 2 days to figure this out and googling did not help at the time.

June 4, 2010

CSS List-Based Tables

This morning I needed to put together a layout for a demo. It was previously done with HTML Tables (there is nothing wrong with using tables when you've got to use tables), however, I've felt the need to convert it into a CSS-list-ish table instead. A couple of hours of looking around the Internet and I couldn't really find what I needed. So I came up with the following which satisfies my requirements in running seamlessly in the latest browsers. I haven't checked it out in Internet Explorer however, so not too sure how it'd do there. But for my current requirement, it works perfectly. Here's the CSS code for the stylesheet:

/* here is our table */
.table {
  display: table;
  border-collapse: collapse;
  margin-left: auto;
  margin-right: auto;
  width: 95%;
  overflow: auto;
  text-align: left;
  border-top: 1px solid #CCC;
  border-right: 1px solid #CCC;
}

.table ul {
  display: table-row;
  list-style: none;
  height: 2em;
  width: 100%;
}

.table ul li {
  display: table-cell;
  height: 2em;
  border-left: 1px solid #CCC;
  border-bottom: 1px solid #CCC;
  padding: 0.5em 0.5em;
  width:10%;
}

.table ul.header {
  height: 2.5em;
  background: #EEE;
}

.table ul.header li {
  height: 2.5em;
  text-align: left;
  font-weight: bold;
  font-size: 1em;
  padding-top: 0.7em;
  padding-bottom: 0;
}

A typical example of using the stylesheet above would look as follows:

  • Product Name
  • Product Code
  • Unit Price
  • Quantity
  • MacBook Pro
  • ML-1025a
  • USD 1500
  • 2
  • Google Nexus One
  • GNO-v1.0
  • USD 499
  • 10

Well that's it. Hope someone finds it useful.

October 17, 2009

Implementing Syntax Highlighting on your blog / website

One of things that has always been missing on my blog as a techie and programmer (and you can judge that from older posts) was a Language / Script Syntax Highlighter. Sometime last week I finally decided to work on a solution for this. Before I continue, credits where they are due (no need to re-invent the wheel if it's already been done, right?):

  • Loading external Javascript files: depending on your situation, you might need to load all the Javascript files that you require from an external server. For example, if you are exclusively using the Blogger platform like I am, you may need to load your files externally as you cannot per-say upload them to the blogger server for use in your scripts. In order to do this, I found a very useful script here: Snipplr LoadScript Function.
  • SyntaxHighlighter: This is a fully functional self-contained code syntax highlighter developed in Javascript by Alex Gorbatchev.
After a bit of Googling, I found my perfect solution. It's called SyntaxHighlighter and has been around for quite a while (since 2004). However, when you Google for it, the first links that show up are that of older versions. SyntaxHighlighter is a work in progress and is already on version 2.x.x. So let's dive straight into the code. The first step you'd like to take loading the style sheets that you'd like to use for your code listing. There is the essential / core one which is shCore.css. Once that's loaded, you should have a look at the various available themes to see which one you'd like to use. Head over here. I personally prefer the default theme as it fits with the white and plain color scheme of my blog. Once all the decisions above have been made, you should go ahead and add the following lines of code to the "head" tag of your blog:

<link href='http://alexgorbatchev.com/pub/sh/2.0.320/styles/shCore.css' rel='stylesheet' type='text/css'/>
<link href='http://alexgorbatchev.com/pub/sh/2.0.320/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/>

Note that you can replace the default theme by looking at the available files available here. Once you're satisfied with the styling, you can move on to the first interesting section of the implementation.

First, add in the script that's needed to load external Javascript files. Also, you'd like to define a URI variable that will be used to refer to the main URI where your files will be loaded from. In the script below, the variable loadURI has been created just for that purpose. As per the reference above, we will use the loadScript function. Right under the previous CSS links we created, add the following lines of code:

<script type="text/javascript">
//<![CDATA[
// let's define a variable for the URL, making it easier to change
// should the case arise
var loadURI = 'http://alexgorbatchev.com/pub/sh/2.0.320/scripts/';

// reference: http://snipplr.com/view/18756/loadscript/
function loadScript(url, callback){

 var script = document.createElement("script")
 script.type = "text/javascript";

 if (script.readyState){  //IE
  script.onreadystatechange = function(){
   if (script.readyState == "loaded" || script.readyState == "complete") {
     script.onreadystatechange = null;
     callback();
   }
  };
 } else {  //Others
  script.onload = function(){
   callback();
  };
 }

 script.src = url;
 document.getElementsByTagName("head")[0].appendChild(script);
}
//]]>
</script>

The script above will allow you to load all the subsequent Javascript files you'd like to use from the external server. As specified before, this is very useful if you are not able to host the files on your blogging platform. It's time to use the script above. Assuming that you'd like to load the scripts straight from the servers where they're published (cautionary note: you should not be doing this), you'd add the following lines to the script above:

loadScript(loadURI + 'shCore.js', function(){
 loadScript(loadURI + 'shBrushCss.js', function(){});
 loadScript(loadURI + 'shBrushSql.js', function(){});
 loadScript(loadURI + 'shBrushPhp.js', function(){});
 loadScript(loadURI + 'shBrushJava.js', function(){});
 loadScript(loadURI + 'shBrushJScript.js', function(){});
 loadScript(loadURI + 'shBrushBash.js', function(){});
 loadScript(loadURI + 'shBrushXml.js', function(){});
 initSyntaxHighlighter();
});

As you can see, the scripts that I've added are those for the languages I'd like to support on my blog. Basically, with the above, the following languages will be automatically supported: CSS, SQL, PHP, Java, Javascript, Bash. Obviously, we all have different needs. In order to see what fits your needs, you should have a look at the following page: Bundled Syntaxes. Head over here to see what the concrete names of the files are. Once you've decided on the scripts that you need, all you have to do is to make sure they're loaded in the main template of your blog / website or you could write some script that would load them dynamically on demand. One essential point to note is that the shCore.js definitely needs to be the first one to be included as per my example above. Once loaded, we use the callback functionality of the loadScript function to load the remaining scripts. This ensures that shCore.js is all loaded into the browser before downloading the other script files. Not doing it this way (as I have learned) would results in Reference Errors in WebKit (engine behind Safari, Opera, Google Chrome, etc...). After all the loadScript calls, there is an aditional function initSyntaxHighlighter() call, which will be explained further down the line. All in all the full script should now be looking like this:

<script type="text/javascript">
//<![CDATA[
// reference: http://snipplr.com/view/18756/loadscript/
function loadScript(url, callback){

 var script = document.createElement("script")
 script.type = "text/javascript";

 if (script.readyState){  //IE
  script.onreadystatechange = function(){
   if (script.readyState == "loaded" || script.readyState == "complete") {
     script.onreadystatechange = null;
     callback();
   }
  };
 } else {  //Others
  script.onload = function(){
   callback();
  };
 }

 script.src = url;
 document.getElementsByTagName("head")[0].appendChild(script);
}

// load the scripts for the language we'd like 
// to have syntax highlighting for on our blog / website
loadScript(loadURI + 'shCore.js', function(){
 loadScript(loadURI + 'shBrushCss.js', function(){});
 loadScript(loadURI + 'shBrushSql.js', function(){});
 loadScript(loadURI + 'shBrushPhp.js', function(){});
 loadScript(loadURI + 'shBrushJava.js', function(){});
 loadScript(loadURI + 'shBrushJScript.js', function(){});
 loadScript(loadURI + 'shBrushBash.js', function(){});
 loadScript(loadURI + 'shBrushXml.js', function(){});
 initSyntaxHighlighter();
});

//]]>
</script> 


The SyntaxHighlighter is almost setup. The next step will be to have a look at how you'd like to configure it. My own configuration is very basic. For more info on all the options as far as the configuration of the script is concerned, you should check the SyntaxHighliter Configuration wiki page. For a very simple and basic configuration, append the following lines of code to the previous one:

function initSyntaxHighlighter()
 {
  SyntaxHighlighter.bloggerMode = true; // set to false or remove if not on blogger platform
  SyntaxHighlighter.stripBrs = false;
  SyntaxHighlighter.clipboardSwf = loadURI + 'clipboard.swf';
  SyntaxHighlighter.all();
 }

Pay attention to the name of this function. It's the same function we call in the loadScript callback of shCore.js. We call it at that stage for the same reason as earlier: avoiding variable or class name Reference Errors in WebKit.

What you may notice here is that I have set the bloggerMode to true. This is because I am hosting my configuration on the blogger platform. If you're hosting on a non-blogger platform, make sure to set that configuration parameter to false or remove that line of code altogether. Once you're happy with the configuration above, you should go ahead and test it. To use see results of all the hard work above, you'd use CSS classes related to the syntax highlighting languages you've included. An example of using it for a bash script for example would be as follows

<pre class="brush: bash;">
  !#/bin/bash
  echo "hello world!"
  export $path:/something/somewhere
</pre>

You will notice the use of "brush" in the class. That's just how you'd use it. So, if you were to need a Javascript syntax highlight, all you'd have to do is to use the "pre" tag or any other tag that you'd specify although "pre" is pretty convenient and add the class as follows: class="brush: html;". This works almost the same way as when adding the style attribute to your tags.

Here's a screenshot of what you will get if everything got properly setup:



Hope this helps anyone else who is looking for a way to have syntax highlighting on their websites or blogs. I find it extremely useful and it's first usage on my blog has been for this post.

Note:I have added all of the sample code above in a one example HTML file which can be downloaded here: Sample Demo File.

Update:You should also download the following PNG files and make sure that they are in the same directory as the CSS files you've linked above. The files are: