I’d like to speak about liveness, it has been introduced in Xcode 6 and along with storyboard and interface preview is a great way to help you undestand how your application will look like without even launching on the simulator.
Watching the documentation I thought it was possible only by creating a subclass of UIView (or UIControl) programatically, while instead is possible to build our own UIView implementation and attach a xib file to it.
This is really helpful, for instance if you need to create a complex layout in a view building it with interface builder is a lot easier instead of coding each constraints.
How to do that?
1. Create a custom UIView subclass and a xib files, that we will name after our own class name: in our case MemeView. Inside the Meme View class remember to define it as designable, by adding the @IBDesignable attribute before the class declaration
2. Rember to set the File’s Owner in the xib with our custom UIView subclass in Indetity Inspector panel

Memeview custom class
3. In the xib file now we can build our interface, make constraints, create outlets, actions etc.

Meme view connection
4. We need to implement few methods to our custom class to open the xib once initialized

    weak var nibView: UIView!

    override convenience init(frame: CGRect) {
        let nibName = NSStringFromClass(self.dynamicType).componentsSeparatedByString(".").last!
        self.init(nibName: nibName)

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        let nibName = NSStringFromClass(self.dynamicType).componentsSeparatedByString(".").last!
        let nib = loadNib(nibName)
        nib.frame = bounds
        nib.translatesAutoresizingMaskIntoConstraints = false
        nibView = nib

    init(nibName: String) {
        super.init(frame: CGRectZero)
        let nibName = NSStringFromClass(self.dynamicType).componentsSeparatedByString(".").last!
        let nib = loadNib(nibName)
        nib.frame = bounds
        nib.translatesAutoresizingMaskIntoConstraints = false
        nibView = nib

    func setUpConstraints() {
        ["V","H"].forEach { (quote) -> () in
            let format = String(format:"\(quote):|[nibView]|")
            addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(format, options: [], metrics: nil, views: ["nibView" : nibView]))

    func loadNib(name: String) -> UIView {
        let bundle = NSBundle(forClass: self.dynamicType)
        let nib = UINib(nibName: name, bundle: bundle)
        let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView

        return view

5. In our custom class we can also define some inspectable properties to have full control over them from interface builder

 @IBInspectable var memeImage: UIImage = UIImage() {
        didSet {
            imageView.image = memeImage
    @IBInspectable var textColor: UIColor = UIColor.whiteColor() {
        didSet {
            label.textColor = textColor
    @IBInspectable var text: String = "" {
        didSet {
            label.text = text
    @IBInspectable var roundedCorners: Bool = false {
        didSet {
            if roundedCorners {
                layer.cornerRadius = 20.0
                clipsToBounds = true
            else {
                layer.cornerRadius = 0.0
                clipsToBounds = false

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var imageView: UIImageView!

In this case swift property observers are super helpful in detect property changes and apply them in real time to out interface.

As a note is worth to mention that not all the types of variable can be inspected (CGPoint, CGSize, CGRect, UIColor, NSRange, UIImage and numbers), for instance if you try to make a font property inspectable it will fail silently and it will not be displayed inside the attribute inspector.

To abstract a little more the xib loading process I created a class subclass of UIView that already takes care of loading “a same class name” xib.

Here are the results.

memeview grumphymeme view koala

If we need to fill with more information the view while it is displayed inside a storyboard or another xib, we can implement prepareForInterfaceBuilder(), this method will be executed only while opening the file in interface builder.

If you did everything I wrote but nothing is working, there is a way to debug a sigle view by adding breakpoints in its implementation.

debug view
You can download this little sample from dropbox.

Oggi nessun articolo di programmazione e niente inglese maccaronico.
Vorrei parlare in realtà di una funzionalità a mio avviso molto interessante presente in iOS8.
A volte può essere utile inserire nel vostro telefono informazioni che siano leggibili a tutti in caso di emergenza senza compromettere la privacy di altre, in pratica aprire una piccola finestra in cui far sbirciare piuttosto che aprire la porta di casa.

Read more!

Finally I had enough time to start working on SWIFT, AFSwiftDateExtension is an NSDate extension that makes working with date an easy task.

Read more!

From iOS7 everything now is about blur. In iOS7 it wasn’t easy to blur a view in “real time”, there are a lot of libraries on GitHub that can  (almost) do that.
On iOS8 Apple came to rescue enabling the UIVisualEffectView.

Let’s see how to implement it.

Read more!

It has been a long time I know, but I was really busy with some important projects.
I’d like to begin the new year with a new post about Pinoccio,  Pinoccio is a micro controller with a built in WiFi and mesh radio with easy access REST API, really useful for build small project for the “internet of things”. For more info read the old article Connect iOS to the internet of things (pinoccio)
The scope of this post is about how to build a simple house power meter and interfacing it with an iOS application.
First of all, to the “capitains” out there must be told that the purpose of the project is not to build a super precise power monitor or explain electrical engineering.

Read more!

One thing that I love about Obj-C and Cocoa is how seamlessly Apple is introducing funcionalities to take advantage of multicore devices.
One of the most common things that a dev does by hourly basis is enumerate a collection.
In Obj-C we can takle this with different approaches:
1 – old plain C for/while loops
2 – fast enumeration protocol (the for..in)
3 – Create an NSEnumerator object from the collection
4 – Use enumeration methods declared in the object interface

The 4th approach is present in almost each kind of collections and one of its methods is the

- (void)enumerateObjectsWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(id obj, BOOL *stop))block

The opts parameter is a bit mask where we can pass this really interesting option:


As the name states this makes the enumeration process a concurrent task and it’s a pleasure to see in instruments the 2 cores working all togheter. There is one caveat as stated by Apple engineers “the code of the block must be safe against concurrent invocation”.

One other stuff that I really love is the way we can help thread safety using blocks.
Recently for a social-instagram-like app I needed to use extensively the AFNetworking library.
To take trace of the networking operation created by each view controller I created a sort of register of the living connection.
The problem in this scenario is the async nature of the process related to the networking tasks. After adding an operation to the register, is impossible to know when it will be  finished (and consequently removed from the register) and this could happen while adding another one the register. We need to put things in order.

To help us we can use a thread locking mechanism,  I’ve found really uselfull the dispatch_barrier mechanism that has less overhead compared to an exclusive lock.

First we need to create our concurrent queue.
In the reading method we create a synch block that waits for the reading to end, if more cores are avalaible more reading request can occur, in the writing method we use a barrier to be sure that no other code has access until the writing finishes. Since GCD queue are executed in first in – first out order we can guarantee that the block would be executed in the same order we have requested.
As you can see from the picture (taken from the book Effective Obj-C 2.0) while the writing block is executing no reading (or writing) can happen.

Read-Write process

Read-Write process

In code is pretty much something like that.

First we create a our concurrent queue

syncQueue = dispatch_queue_create("it.shootshare.registeroperation", DISPATCH_QUEUE_CONCURRENT);

Then we override our properties:

- (NSString*) name {
  NSString * __block aName = nil;
  dispatch_sync(syncQueue, ^{
     aName = _name;
  return aName;

- (void) setName:(NSString*)aName {
   dispatch_barrier_async(syncQueue, ^{
     _name = aName;

I don’t want to start explaining what is “the internet of things” because it’s a really huge topic, but I’m here to share my first experience into connect an iOS device to a micro controller called Pinoccio and what that means.

What is Pinoccio? am I missing an “H”?

Is really hard to describe it, I’m really proud about being a funder of this project on indiegogo.

Pinoccio at a first first look seems to be like a pumped Arduino with a WiFi shield and mesh radio communication. If you are wondering.. yes is compatible with the Arduino IDE and you can compile your own custom firmware, but do we really need that? Building a firmware with the Arduino IDE that include a network library, shield communication can be really frustrating, if you are not familiar with micro-controllers, is really a long hard road. For instance the memory is a big problem into creating a sort of web-server that can run into a micro-controller.
One of my first desire when I ‘ve got my first iPod Touch was to connect my device on everything and when I started to build my own applications using the iphone sdk, I always tried to figure out how to do that, but I’ve found huge obstacles that I wasn’t still prepared to tackle.
In the earlier realeses of iOS version wasn’t possible to connect the iphone to a sort of prototype board, well not exactly but I have should enroll to the made for iphone/ipod program and the process wasn’t really easy. The accessory framework had very few documentation available to the public. Now we can use the Bluetooth LE to connect with an accessory but it seems to be locked for 1:1 connection (but I’m not totally sure about it, for instance the multipeer connectivity can connect up to 8 devices).
Then I started to use Arduino a little, but the problem was still the connection between the 2 devices, the only option was using the ethernet shield, build something like a webserver and access Arduino pins with a sort of web services. Not so easy and also with a lot of limits about memory, bottlenecks etc in my mind I couldn’t find a way to do something that could be ready for production.

Later Redspark started to sell a cable (in compliance with the made for iphone program). With this cable is possible using the serial communication to make an Arduino talk with an ios device, but under current Apple policy this cable may not be used with apps sold on the App Store.

Then I’ve found ElectricImp, I was really interested into that project but when I heard that I would always need to stay bounded to their cloud platform I gave up, but the Imp is a really cool device if you accept that limitation (or feature).
On Febraury 2013 during an Indiegogo campaign I heard about Pinocc.io it was love at first sight.

Pinoccio image

Pinoccio with all its features

Why Pinoccio changes everything?

  • It is a really small and cool prototyping board.
  • They are making an FCC certified version for production of a size of a nail.
  • You can build you own firmware in the old Arduino way.
  • You can use a scripting language to communicate with it from a web terminal (and via REST).
  • You can log it and launch those script commands using REST webservices.
  • You are not bound to use their platform.
  • You can create your own mesh of pinocc.ios and only one of them need to comminicate WiFi.
  • You can create your own custom script (maybe because you need to communicate in a specific way with a sensor or peripheral)
  • It’s all wireless
Pinocc.io Web interface

Pinocc.io Web interface

It’s pretty clear that you can do almost everything you want.

The idea here is to send all your request to their (or yours) platform and read or write properties with simple calls on the the platform, and this is a reallu smart idea, because most probably the platform manages the traffic on the board, maybe also caching some responses, avoiding bottle necks or massive requests.

To make a simple example about how this board connected to you iOS device can be powerful, I’ve made an easy app that asks the on-board temperature of the two scouts.
We have a lead scout (Optimus Prime) with the Wi-Fi backpack on it and the other scout (Bumble Bee) that communicates through the lead scout.
The lead scout is installed in my home and the other outside – of course the on board temperature is not the real environment temperature because is due to the load of the CPU and the environment temperature itself-.

Pinoccio temperature app

A video can be found here.

This is a simple example but let me try to figure out something bigger.

Let’s imagine that each scout has a Bluetooth LE backpack and a simple OLED display installed in a shoes shop. Each shoes has its own scout (like a price tag) with the display that shows the like/reviews numbers.
Each scout sends an iBeacon signal to identify a specific product close to them. When a user get close to the product using the shop application connects to that scout/ibeacon and get the product details, there is also the possibility to “like” it, once the use press like on the phone the like number on the display is incremented almost in real-time.
The other interesting example could be to measure the energy consumption of our house integrating a hall effect sensor on each scout and display data in a cool web page or into your mobile phone.

Arduino in my opinion created a revolution opening the market to all those boards, these is just the beginning because the revolution of the DIY is cultural and educational.
I hope to have more time to play around using Pinocc.io and this is the first time that I feel I have something “ready for production” and not just a new cool R&D gadget.

I’ m working on a photo app with a lot of technical challenges to tackle, but I hate when you spend a lot of times on stupid things mostly due to the lack of documentation. EXIF orientation flag is one of them, so let’s try to explain it.

An image can contain additional information, those info can be stored inside the EXIF format specification.

EXIF Tags (or metadata) cover a lot of different aspects:

- timestamp information

- camera settings (such as ISO,white balance, orintation)

- a thumb image

- geographical coordination

- other descriptions and copyright info

Orientation flag is based on the rotation of the camera respect to the ground (and probably the scan directions of the image).

iOS cameras follow the same rules as new digital camera, so the EXIF orientation flag is a reality, the problem is that conflicts somehow with the UIKit defined enumeration for UIImage orientations.

typedef enum {
 UIImageOrientationUp =            0, // 0 deg rotation exif 1
 UIImageOrientationDown =          1, // 180 deg rotation exif 3
 UIImageOrientationLeft =          2, // 90 deg CCW exif 6
 UIImageOrientationRight =         3, // 90 deg CW exif 8
 UIImageOrientationUpMirrored =    4, // horizontal flip exif 2
 UIImageOrientationDownMirrored =  5, // horizontal flip exif 4
 UIImageOrientationLeftMirrored =  6, // vertical flip exif 5
 UIImageOrientationRightMirrored = 7, // vertical flip exif 7
} UIImageOrientation;

Let’s see how orientations behave during 3 different kinds of image acquisition.

We will start with UIImagePickerController. Doing some experiment shooting and rotating the device we obtain this table.

Using back camera:

DeviceOrientation UIImageOrientation EXIF
Portrait UIImageOrientationRight 6
LandRight UIImageOrientationUp 1(default)
LandLeft UIImageOrientationDown 3
PotraitUpsideDown UIImageOrientationLeft 8

With front camera:

DeviceOrientation UIImageOrientation EXIF
Portrait UIImageOrientationRight 6
LandRight UIImageOrientationDown 3
LandLeft UIImageOrientationUp 1
PotraitUpsideDown UIImageOrientationLeft 8

To obtain those data you just need to add those few lines of code inside the delgate method:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
 // ...
 UIImage * originalImage = (UIImage *) [info objectForKey:  UIImagePickerControllerOriginalImage];
 NSDictionary *i mageMetadata = [info objectForKey: UIImagePickerControllerMediaMetadata];
 NSLog(@"Metadata Exif Orientation: %@   UIImageOrientation %d", imageMetadata[(NSString*)kCGImagePropertyOrientation],   originalImage.imageOrientation);

Using AVStillImageOutput things change. Avoiding the orientation correction that we could apply using -videoOutputOrientation on AVCaptureConnection we will obtain always the same number, the exif orientation number 6

 [[self stillImageOutput] captureStillImageAsynchronouslyFromConnection:[[self stillImageOutput] connectionWithMediaType:AVMediaTypeVideo]
completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
 CFDictionaryRef attachments = CMCopyDictionaryOfAttachments(kCFAllocatorDefault, imageDataSampleBuffer, kCMAttachmentMode_ShouldPropagate);
 NSLog(@" Metadata %@", (__bridge NSDictionary*)attachments);
 // ...

The same happens when we play with AVCaptureVideoDataOutput delegate method. Each frame is returned with orientation number 1, that means that we need to fix that programmatically, and that is what Apple does in the SquareCam sample code. They get the device orientation and convert it into EXIF.

 /* kCGImagePropertyOrientation values
 The intended display orientation of the image. If present, this key is a CFNumber value with the same value as defined
 by the TIFF and EXIF specifications -- see enumeration of integer constants.
 The value specified where the origin (0,0) of the image is located. If not present, a value of 1 is assumed.
 used when calling featuresInImage: options: The value for this key is an integer NSNumber from 1..8 as found in kCGImagePropertyOrientation.
 If present, the detection will be done based on that orientation but the coordinates in the returned features will still be based on those of the image. */
 enum {
  PHOTOS_EXIF_0ROW_TOP_0COL_LEFT          = 1, //   1  =  0th row is at the top, and 0th column is on the left (THE DEFAULT).
  PHOTOS_EXIF_0ROW_TOP_0COL_RIGHT         = 2, //   2  =  0th row is at the top, and 0th column is on the right.
  PHOTOS_EXIF_0ROW_BOTTOM_0COL_RIGHT      = 3, //   3  =  0th row is at the bottom, and 0th column is on the right.
  PHOTOS_EXIF_0ROW_BOTTOM_0COL_LEFT       = 4, //   4  =  0th row is at the bottom, and 0th column is on the left.
  PHOTOS_EXIF_0ROW_LEFT_0COL_TOP          = 5, //   5  =  0th row is on the left, and 0th column is the top.
  PHOTOS_EXIF_0ROW_RIGHT_0COL_TOP         = 6, //   6  =  0th row is on the right, and 0th column is the top.
  PHOTOS_EXIF_0ROW_RIGHT_0COL_BOTTOM      = 7, //   7  =  0th row is on the right, and 0th column is the bottom.
  PHOTOS_EXIF_0ROW_LEFT_0COL_BOTTOM       = 8  //   8  =  0th row is on the left, and 0th column is the bottom.
 switch (curDeviceOrientation) {
  case UIDeviceOrientationPortraitUpsideDown:  // Device oriented vertically, home button on the top
   exifOrientation = PHOTOS_EXIF_0ROW_LEFT_0COL_BOTTOM;
  case UIDeviceOrientationLandscapeLeft:       // Device oriented horizontally, home button on the right
   if (isUsingFrontFacingCamera)
    exifOrientation = PHOTOS_EXIF_0ROW_BOTTOM_0COL_RIGHT;
    exifOrientation = PHOTOS_EXIF_0ROW_TOP_0COL_LEFT;
  case UIDeviceOrientationLandscapeRight:      // Device oriented horizontally, home button on the left
   if (isUsingFrontFacingCamera)
    exifOrientation = PHOTOS_EXIF_0ROW_TOP_0COL_LEFT;
    exifOrientation = PHOTOS_EXIF_0ROW_BOTTOM_0COL_RIGHT;
  case UIDeviceOrientationPortrait:            // Device oriented vertically, home button on the bottom
   exifOrientation = PHOTOS_EXIF_0ROW_RIGHT_0COL_TOP;

EXIF dictionary is not supported by all image formats, for instance PNG doesn’t support it. When we create a UIImage from a source (disk, remote) and the image raw data contains this flag is automatically converted into a UIImageOrientation value. This is really important also when we save an image, if we don’t bring it during the saving operation, the saved image will be shown in a wrong way.

Erika Sadun has made a very helpful pack of  methods and functions to use the camera in the right way also dealing with orientations.

Probably the idea behind UIImageOrientation is that it refers to the difference in degrees to apply if we want a match between the current device orientation and the EXIF flag related to a correct image orientation.

Di recente ho dovuto “smanettare” per un bel po’ di tempo sulle UITableView  con contenuto statico.

Cosa sono le UITableView statiche?

Dal punto di visto dell’utilità sono eccezionali perché in pochissimo tempo, tramite l’editor degli storyboard consentono di creare una lista di celle fissa, statica, nel senso che non può cambiare a runtime (anche se non è completamente esatto perché certi comportamenti possono essere sovrascritti). Ciò comporta il non dover implementare i metodi di data source (UITableViewDataSource).

Lo svantaggio è che non sono celle riutilizzabili, quindi un uso massiccio impatta in maniera negativa sulle performance. Devono essere, pertanto, usate quando il numero di elementi in una UITableView è basso.

Si pensi, ad esempio, di dover comporre una lista di attributi che descrivono l’articolo di un negozio, come:

  • data inserimento articolo
  • pezzi a magazzino
  • costo articolo
  • etc…

Per un requisito del genere una table view statica è un ottimo candidato per creare un’interfaccia di questo tipo. Essa apporta maggiori vantaggi rispetto ad una classica view con label e campi di testo.

Perché ? :

  1. le UITableView sono un elemento estremamente “mantenibile”: se volessi aggiungere una voce mi basterebbe aggiungere un’altra row
  2. le UITableView ereditano dalle  UIScrollView posso anche non preoccuparmi delle diverse dimensioni di schermo
  3. non c’è bisogno di impazzire dietro ad autolayout
  4. non è necessario implementare i metodi di datasource
  5. se l’ interfaccia presenta dei campi da occultare in alcuni casi posso semplicemente dire alla tableview che a quell’index path per quel specifico caso l’altezza è 0 (solo per UITableViewController)

Mi occuperò, dunque, proprio dell’altezza delle UITableViewCell. Uno degli ostacoli forse più difficili da superare nell’utilizzo di queste è riuscire a creare delle celle di altezza variabile che si adattino al contenuto. Per capirci, è sufficiente pensare a quelle di what’s app o dell’applicazione messaggi.

L’altezza delle UITableViewCell viene infatti calcolata prima che queste vengano create e renderizzate a schermo perché le altezze sono necessarie per calcolare la contentSize della UIScrollView; una soluzione spesso adottata è quella di creare un modello di altezze, ovvero si precalcolano le altezze prima di visualizzare le celle per poi passare questo dato nel metodo – tableView:heightForRowAtIndexPath: . Un’operazione che poteva diventare ancora più complessa nel qual caso le celle fossero state di diverso tipo. Ciò comportava la creazione delle celle nella fase di precalcolo in maniera da realizzare tutti i calcoli necessari e fornire un’altezza corretta.

Si era di fronte al classico “collo di bottiglia”. Su table view, in presenza di un grande numero di righe, si poteva  giungere ad una situazione molto fastidiosa: un blocco momentaneo con un ritardo sul caricamento dell’interfaccia.

iOS7 ha introdotto un nuovo metodo – tableView:estimatedHeightForRowAtIndexPath: che rimanda al momento della visualizzazione il richiamo del metodo – tableView:heightForRowAtIndexPath:.

Sostanzialmente richiede una stima che consenta alla UITableView di potersi dare una contentSize di settare le altezze delle scrollbar etc.

Anche in questo caso ci troviamo di fronte ad uno strumento che dovrebbe essere usato solo in certe occasioni. Infatti, il calcolo dell’altezza rimandato durante il caricamento della cella può creare un lag durante lo scrolling percettibile.

La stima da fornire può essere un numero fisso, magari basato su una media ipotetica dei diversi valori che l’altezza può assumere, oppure può essere un calcolo approssimato molto più veloce di quello più preciso.

Un suggerimento che vale la pena menzionare è il caching dei valori già calcolati delle altezze. Se le celle non subiscono modifiche dopo la loro visualizzazione è inutile ricalcolarne l’altezza ogni volta, basta restituire quella in cache.


Visto che l’argomento iBeacon sembra particolarmente interessante ho deciso di fare un video di 13 min con due piccole demo.

Spero possiate trovarlo interessante e perdonate le papere, ma andavo a braccio!!!!

Un altro articolo interessante sullo stesso argomento: iBeacon, behind the scene