iOS Goodies

Just release a new blog to act as a weekly digest for what’s happening in the iOS world (articles, controls, UI). Hope you like it.

Tagged , ,

KirKos: App Development under 24h

Introduction

κίρκος :  circle, mostly in form κρίκος (q.v.): hence, ring, IG11 (2).161B49 (Delos, iii B.C.): poet. for Prose κρίκος acc. to Poll.1.94:—neut. pl. κίρκα ἢ καταδέσματα PMag.Lond.121.299.

 I want to be able to add a blur effect around a picture (with a circle shape), and then save it or share it.

The idea/concept came from Rui Barroca. So, after an initial assessment at a Nando’s restaurant, we reached the following:

  • There were no applications doing this, or doing it how we wanted it to be (on a Business PoV).
  • Blur is a design trend that iOS 7 brought with it, so doing some work on that area is interesting (on a Dev & Designer PoV).
  • Doing so in less than 24hours, was a challenge that I happily embrace.

The concept, design, development and submission, started on a Thursday, 17/10 @ 21:00 and was finished on Monday, 21/10 @ 00:05. It took around 23 hours.

Features

Must Have

  • Take Picture from camera.
  • Pick a photo from the gallery.
  • After selecting/taking the picture, be able to add a blur, with a circle shape, around a picture.
  • Be able to define the blur’s radius.
  • Save the picture with the blur effect on the Phone’s Gallery.

Could Have

  • Share the picture on the most common social networks.
  • Be able to use Instagram’s URL scheme and open the picture on Instagram, so it can be edited. 

Nice to Have

  • About Screen.
  • Pan Gesture, to resize the circle.
  • One finger gesture, to change the circle’s center. 

As you might expect, the “Nice to Have” section is out from the first version of the app. In our opinion, it will make sense, if we have enough people using it.  The “Must Have” was kept: even though we don’t bring a lot of features with KirKos, we wanted to make sure that what it does, does well, so we made sure the core functionality was there, from day one. Because we still had some time, the “Share the picture on the most common social networks.” is an integral part of the first version.  In the end, adding and removing features is hard, but you should focus on what’s the purpose of your application and that it delivers it seamlessly.

Design

This is the Design version 1.0. With the Selection of the photo on the left, and the edition on the right:

1.0_KirKos_CaptureScreenv_v0.1                             1.1_KirKos_EditShareScreenv_v0.1

This is version 2.0:

1.0_KirKos_CaptureScreen_v0.2                             1.1_KirKos_EditShareScreen_v0.2

On a first look, the difference is not that big. But  take into consideration that  version 1, just doesn’t work  with 3.5′ iPhone, due to the menu where you have the flash &  switch front/rear camera, you couldn’t accomodate that in 3.5′. So on version 2.0, we pushed the flash and “switch front/back camera” to the camera area.  This gave us a bit more room for the 4′ version, and decent UI for the 3.5′. We also decided to separate the “Share Button” and the “Save Button”. The initial purpose was to be able to save the image on the phone, but sharing it, on the long run, is more important, so we keep the Share button on the mid. You are also able to save it on your gallery by pressing the “Share Button”, but for the time being we will keep as it is.

Development

The first question that popped into my mind was how could I create the Blur? Fortunately, in that matter, we have quite a lot to choose from. The initial design of the app, was to allow the user to apply the filter while the camera was on, this is very important to decide which 3rd party lib you are going to use. After knowing that FXBlurView wouldn’t work as I wanted, I gave GPUImage  a try. Not sure why, I wasn’t able to put it to work on my first try, so I decided to use the same workflow as Instagram:

Pick/Take Photo -> Apply Filter -> Share 

On the long run, this brings a couple of advantages:

  • Better performance for older devices. I am confident that live camera + effect, would translate into low fps.
  • A single place for editing the picture. With this I have more space to show editing controls, and remove the ones used for taking the picture

Since Business side was ok with this change, we move forward with it.  For this kind of flow, FXBlurView proved to be more than enough.  Some facts about the development and the code:

  • One of the places where I lost  a lot of time (and wasn’t really expecting to), was trying to put a UIImagePickerController's root UIView as a subview of my UIViewController's root UIView and keep the Status Bar visible.
  • The total amount of line of codes is  around 650. The biggest class is 298 lines.
  • I am using two nibs, one for 4′ and another 3.5′, with Auto Layout. This approach revealed to be more practical to maintain.
  • The size of the project is 4.3mb.
  • I made one question on stackoverflow regarding the creation of the app,  which I answered myself.
  • Used three 3rd party libs: FXBlurView, UIImage+Orientation, UIColor+Hex. The last two, are classes I created but with other people’s code.

Conclusion

Having two persons, in this case me and Rui, wanting the same thing, really paid of. The fact of being able to ask him an asset, or an approach on something, and being able to receive feedback immediately proved to work (even while working remotely). Without this, it would be impossible to finish it in such a short period of time. I have to say this was a very fun experience and I will definitely repeat it. Finally, the application can be downloaded here.

Note: The source code is available here: https://github.com/RuiAAPeres/KirKos. If you like it, please Star it.

 

Tagged , , , , , , , , , ,

Architecting with Blocks part 2

(Note: This is part 2 of a series of posts about Architecting an application using blocks in objective-c. By no means I am an expert on using blocks, and also it’s not the intention of this series to teach you how to use blocks. You can check this for that. To finalise, I am sure there are better ways to use blocks while architecting an app: use this at your own risk. :))

This is the final post from a 2 parts series that I start a long ago. In this case I won’t show any snippet of code, I will give away an entire sample. My approach about this matter, change in the meantime, nonetheless hope you enjoy it. You can find it here .

Tagged , , , , , , ,

Deploying Node.js to production

Node.js community has not yet defined any standard or a good practice for deploying applications. And dealing with production caos can be a total pain in the butt. Fortunately after searching a lot over the web, I found some consensus and tips for deploying a Node.js app to production.

  • Express
  • If you typically use Express like me, you can set up the configs for your deployment modes (development, production, etc) in the main file. The below config is simple but easily extensible for supporting your needs. Here I just set the exception verbosity and an initializer for the MongoDB connection which can differ between the deployment modes:

    app.configure('development', function () {
      app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
      mongo.connect('development',logger); // mongodb initialization
    });
    
    app.configure('production', function () {
      app.use(express.errorHandler());
      mongo.connect('production',logger); // mongodb initialization
    });
    
  • Uncaughts Exceptions
  • A Node.js app (without forking or cluster facilities) runs on a single process. An uncaught exception can totally tear your instance down, stopping your service from responding to client’s requests. One way for surpassing this issue is to listen to ‘uncaughtException’, log the error and gracefully shutdown the process.

    process.on('uncaughtException', function (err) {
      console.error('uncaughtException:', err.message)
      console.error(err.stack)
      process.exit(1)})
    
  • Process Manager
  • However, even with this safety measure, your service is offline and doesn’t respond to any requests. First of all, you can daemonize your app by using Linux Upstart so the node process could run in background (forget about screen multiplexing or leaving the terminal open all day!).

    On Debian systems (Ubuntu, etc) run this for installing Upstart:

    $ sudo apt-get install upstart
    

    Ok good, now create a new file (/etc/init/nodeapp.conf) for configuring your new daemon. I borrowed this config and made some little changes:

    #/etc/init/myapp.conf
    description "Node App"
    author "me"
     
    start on startup # it's possible to use "net-device-up IFACE=eth0" for starting the process when the ethernet adapter is up
    stop on shutdown
    
    script
            cd /home/me/nodeapp
            exec sudo -u ubuntu NODE_ENV=production /usr/bin/node /home/me/nodeapp/app.js >> /home/me/nodeapp/log/app.log 2>&1
    end script
    

    In this simple config I teel Upstart to auto-start the process on boot and log output to a specific log file. Upstart also gives you some basics commands for managing the daemon:

    $ start nodeapp
    $ stop nodeapp
    
  • Monit
  • Having your app daemonized doesn’t save yourself from waking up at 3am because of some crashing activity (uncaught exceptions, network timeouts, etc). The rescue tool is Monit. Monit is a awesome utility which monitor and manage processes, files, directories, networking connections on Unix systems. Under the hood it just runs tests in certain intervals and proactively takes some action based on configured rules.

    On Debian systems (Ubuntu, etc) run this for installing Monit:

    $ sudo apt-get install monit
    

    Open “/etc/monit/monitrc” and uncomment the “set httpd” to be able to monitor on localhost:

    set httpd port 2812
        use address localhost  # only accept connection from localhost
    

    This test rule will check if the node and mongodb processes responds to HTTP requests:

     check host nodeapp with address 127.0.0.1
               start "/sbin/start nodeapp"
               stop "/sbin/stop nodeapp"
               if failed port 3004 protocol HTTP
                        request /
                        with timeout 5 seconds
                        then restart
                        if 5 restarts within 5 cycles then timeout
               if failed port 28017 protocol HTTP
                        request /
                        with timeout 5 seconds
                        then exec "/sbin/start mongodb"
    

    The DSL is pretty self-explanatory. For the node process running on 3004, the test will check if HTTP requests are failing, wait 5 seconds, restart the process, and if after 5 restarts the instance still doesn’t respond, it will call timeout. On the other side, for the mongo instance running on 28107, the test will checks if HTTP requests are failing, wait 5 seconds, and start a fresh mongodb process.

    Wait! don’t forget to restart monit:

    $ sudo service monit restart
    

    Monit has lots of configurations for dealing with every possible situation. I recommend searching over the web or just checking their website.

    For managing a Apache web server:

    check process apache with pidfile /var/run/apache2.pid
        start program = "/etc/init.d/apache2 start" with timeout 20 seconds
        stop program  = "/etc/init.d/apache2 stop"
        if totalcpu > 20% for 2 cycles then alert
        if totalcpu > 20% for 5 cycles then restart
    

    Alert the sysadmin by mail is something goes wrong:

    set mailserver localhost
    set alert sysadmin@domain.com
    
       set mail-format {
           from:xxxx@gmail.com
         subject: monit alert --  $EVENT $SERVICE
         message: $EVENT Service $SERVICE
                       Date:        $DATE
                       Action:      $ACTION
                       Host:        $HOST
                       Description: $DESCRIPTION
      }
    

    Finally use this command (or the web GUI) for checking the actual monitoring status:

    $ sudo monit status
    The Monit daemon 5.3.2 uptime: 2h 7m 
    
    Remote Host 'nodeapp'
      status                            Online with all services
      monitoring status                 Monitored
      port response time                0.000s to 127.0.0.1:28017/ [HTTP via TCP]
      port response time                0.001s to 127.0.0.1:3004/ [HTTP via TCP]
      data collected                    Fri, 26 Sep 2013 19:31:00
    
    System 'system_Server'
      status                            Running
      monitoring status                 Monitored
      load average                      [0.01] [0.02] [0.05]
      cpu                               0.1%us 0.2%sy 0.1%wa
      memory usage                      791252 kB [19.5%]
      swap usage                        0 kB [0.0%]
      data collected                    Fri, 26 Sep 2013 19:31:00
    
  • Git
  • Finally the deployment process per-se.

    Set your development environment by editing “~/.ssh/config”:

    Host nodeapp
    Hostname nodeapp-server.com
    
    IdentityFile ~/.ssh/mykey.pem
    User me
    

    Next create a bare (empty) git repo on the server:

    $ mkdir nodeapp.git
    $ cd nodeapp.git
    $ git init --bare
    

    And a git hook in “~/nodeapp.git/hooks/post-receive” for automatically restarting your node process with the deployed modifications:

    #!/bin/sh
     
    GIT_WORK_TREE=/home/me/nodeapp git checkout -f
     
    echo "Restarting node process..."
    sudo restart nodeapp
    
    

    Back in your development machine, add the remote repo to your local setup:

    $ git remote add origin ssh://nodeapp/home/me/nodeapp.git
    

    And finally push the code!

    $ git push origin nodeapp
    

    In this post I only presented some tools and tricks for deploying to production without fear. Eventually you will need to setup a reverse proxy as Nginx in front of your processes for load balancing between them or just for serving static assets and error pages. I will talk about Nginx in a future post. Good hacking!

    Tagged , , , ,

    Integration Tests for Web Services Using RSpec

    Recently I had to implement a REST web service for a project in Rails. I’ve been using RSpec for every kind of tests for a long time but, still, wasn’t sure on what was the best way to use it to test a web service.

    Capybara has always been my first choice for integration tests, but it doesn’t make much sense if your views are just plain JSON. Thus, I went for a leaner approach taking advantage of Rack::Test::Methods.

    In this post I will explain my approach to test a web service. I won’t get into any details on how the web service in question could or should be implemented.

    Setup

    The first thing to setup is the filesystem. There are infinite ways to do this, I prefer to keep the API tests isolated from the rest of the application.

    spec
      ├── api
      │
      ├── controllers
      │
      ├── factories
      │
      ├── features
      │
      ├── models
      │
      ├── spec_helper.rb
      │
      └── support
    

    I guess it would also make sense to decide to put the tests for your API inside the features folder, but I prefer to create a separate api folder. It just feels cleaner.

    There’s only one more step to complete the setup. We need the Rack::Test::Methods module in our tests. For convenience let’s add it to the spec_helper.rb.

    # ...
    RSpec.configure do |config|
      config.include Rack::Test::Methods
      # ...
    end
    

    That’s it! No more setup needed, let’s write some specs!

    Specs

    For the sake of example let’s say we are building an application that, for some reason, manages products.

    I always create one file for each endpoint. Since we’re managing products, there should be an endpoint for products. Therefore there is a spec file named products_spec.rb inside our spec/api folder.

    require 'spec_helper'
    
    describe '/api/products', type: :api do
      # ...
    end
    

    The main describe block clearly states that we’re describing the /api/products endpoint spec in this file. The describe block as a type of api, the type property is not very important in this case, but it can be used to create filters. More info about that here.

    Inside the main describe block we can describe the several actions available at this endpoint, like index, show… This is where all the magic happens.

    describe '#index' do
      before { get api_products_path }
    
      it { last_response.status.should eq 200 }
    
      it 'should return 10 products' do
        products = JSON.parse last_response.body
        products.count.should eq 10
      end
    end
    

    On this example we are testing the index action for the /api/products endpoint. We have a before hook that sends a get request to api_products_path. This means that get api_products_path will execute before each it block.

    My favourite part of it is that we have the method last_response. This method returns the response for the last request made in the script and we can use it to access the status of the response, the body, header, etc… All courtesy of Rack::Test::Methods. You can check the documentation for other methods that you may need.

    Btw, the get method is also part of the Rack::Test::Methods module. There’s also methods for the other types of requests, post, put, patch, delete, etc…

    Conclusion

    • Integration tests for you API should be isolated from the rest of your test suite;
    • Each spec file should have the specs for an endpoint;
    • You don’t need a complex framework for this kind of tests, Rack::Test::Methods works just fine;

    Matz, why?

    In “The Well Grounded Rubyist”, David Black talks about the “Class/Object Chicken-and-Egg Paradox”:

    The class Class is an instance of itself; that is, it’s a Class object. And there’s more. Remember the class Object? Well, Object is a class… but classes are objects. So, Object is an object. And Class is a class. And Object is a class, and Class is an object.

    Tagged , , , , ,

    Item 3, Prefer Literal Syntax over the Equivalent Methods

    Note: This post is part 3 of a series of posts I will do about the new book of Matt Galloway.

    Prefer Literal Syntax over the Equivalent Methods

    Literals have been around objective-c since a long time:

    NSString *aString = @"Hello World";

    With the latest versions of Clang, this sugar syntax has been extended to NSNumbers, NSArrays & NSDictionaries. Since we deal with this kind of objects every day, this new feature is well appreciated. In a nutshell this allow us to:

    • Reduce the boilerplate
    • Cleaner code
    • Faster typing

    While using NSNumbers, you can use literals in the following way:

    • @15 => [NSNumber numberWithInt:15]
    • @15.6 =>[NSNumber numberWithFloat:15.6]
    • @15.123123 => [NSNumber numberWithDouble:15.123123]
    • @YES => [NSNumber numberWithBool:YES]

    As you can see, in this case, the amount of extra code is reduced in more than 75%.

    You can also use literals in collections with subscripting. With NSArray you can do the following:

    • @[@"One", @"Two"] => [NSArray arrayWithObjects:@"One",@"Two"];
    • By Array subscripting: myArray[1] => [myArray objectAtIndex:1];

    And finally with a NSDictionary:

    • @{@"key1":@"object1", @"key2":@"object2"} => [NSDictionary dictionaryWithObjectsAndKeys:@"object1",@"key1",@"object2",@"key2" nil];
    • myDictionary[@"key1"] = @"newObject1"; => [dic setObject:@"newObject1" forKey:@"key1"];

    And if you want a mutable object:

    • [@[@"1",@"2" ] mutableCopy];
    • [@{@"key1":@"object1"}mutableCopy];

    Although with collections the end result seems the same, if an object is nil, it won’t. While using the common operations adding a nil wouldn’t crash anything, with literals it will:

    • [NSArray arrayWithObjects:@"object1",nil, @"object2", nil] => It’s “ok”.
    • @[@"object1",nil, @"object2"] => It will raise an exception.

    In theory it would be better if the first option would crash, because it doesn’t make much sense to have a nil in the middle of an array and work with it in that state. Most of the time, you would prefer that would crash, so you could see immediately where the problem is.

    Literals are an awesome addition in a very verbose language like objective-c. Knowing how to use them and their caveats is a must have for every programmer.

    Links:

    Tagged , , , , , , , , ,

    Item 2, Minimize Importing Headers in Headers

    Note: This post is part 2 of a series of posts I will do about the new book of Matt Galloway.

    Minimize Importing Headers in Headers

    The second item, unfortunately a short one, talks about importing classes: the where and the how. One should be careful when importing things he doesn’t need on the .h file. Most of the time, specifying @class (forward declaration) instead of an #import is  the best choice. Importing creates dependences between classes that should be avoided (when possible). So what does this @class actually means?

    “The @class directive minimizes the amount of code seen by the compiler and linker, and is therefore the simplest way to give a forward declaration of a class name. Being simple, it avoids potential problems that may come with importing files that import still other files. For example, if one class declares a statically typed instance variable of another class, and their two interface files import each other, neither class may compile correctly.” – Abizern, http://stackoverflow.com/a/323510/491239.

    So in a nutshell (from Mr. PeyloW, http://stackoverflow.com/a/1350029/491239):

    • Only #import the super class, and adopted protocols, in header files.
    • #import all classes, and protocols, you send messages to in implementation.
    • Forward declarations for everything else.

    And a quick example:

    “The reasoning behind forward declarations in header files is that it avoids unnecessary dependencies. i.e. Imagine B.h forward declares A and B.m imports A.h. Then imagine C.m, D.m, E.m and F.m import B.h. After all this is done, A.h changes. Since A is only forward declared in B.h, only B.m needs to rebuild. Without forward declarations, C.m, D.m, E.m and F.m would all need to be rebuild if A changes” – Jacob Relkin, http://stackoverflow.com/a/2770246/491239

    Hope you enjoyed this quick reference to how to import in objective-c.

    Tagged , , , , , , , ,

    Item 1, Familiarize Yourself with Objective-C’s Roots

    Note: This post is part 1 of a series of posts I will do about the new book of Matt Galloway.

    Familiarize Yourself with Objective-C’s Roots

    Dynamic language

    In this item, the author starts by delving into how Objective-c send messages as opposed of function calling (in this case comparing to C++)  and when one should be used instead of the other (you can still use function calling in objective-c).  The dynamic nature of objective-c, binds the messaging to the corresponding piece of code that will be called, at runtime; as opposed to C++ (for example) that is done at compile time.

    Memory Management

    One should understand how related objective-c is to c (it’s a superset) and how/where the allocations are made:

    NSString *aString = @"BlahBlah";

    In this case “aString” is a pointer to a piece of memory allocated on the heap. Although this is mostly true for allocating objects in objective-c, blocks for example are allocated on the stack, but can be  passed to the heap (block_copy()).  An excellent post by Mike Ashe explains this as well.  Plus when you alloc, new, retain or copy an object, you are responsible for them.  It’s important as well to know how the memory is managed in objective-c:

     ” (..) that any single object can have multiple “owners”, and the system won’t allow the object to be destroyed until all owners have relinquished ownership.” – Mike Ashe,  Stack and Heap Objects in Objective-C

    In one hand with manual memory management, you are responsible for cleaning the house, with ARC the cleanup is being made for you. Do remember, that ARC is not a Garbage collector, so you should need to understand when you have to do something (circular references for example) and when you don’t.

    You will find plenty of variables that will be create on the stack, for example:

    CGPoint point = CGPointMake(12.0f,10.0f);

    CGPoint is a structure and it’s defined like this on CGGeometry.h from CoreGraphycs.framework:

    struct CGPoint {
    
    CGFloat x;
    
    CGFloat y;
    
    };
    typedef struct CGPoint CGPoint;
    

    It’s important to measure if you are going to use objects (vars that point to something that has being allocated on the heap) and, in this case, structures (vars that might be using stack space), or non-objects int,float, char, etc. Allocating objects  can incur on an unnecessary overhead, so chose the right tool for the job in hand.

    The first item, is a very well written intro into how objective-c works internally versus other languages, and how you can take advantage of the C language . As it is build upon it, some time should be taken to understand it.

    Tagged , , , , , , ,