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
        addSubview(nib)
        nibView = nib
        setUpConstraints()
    }

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

    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:

NSEnumerationConcurrent

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.

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

 

L’annuncio degli iBeacon sembra aver scosso un po’ il mercato mobile, come se questi oggetti fossero un qualcosa di magico che consente di fare un po’ tutto, dalla geolocalizzazione indoor, ai pagamenti, dalla casa intelligente, a retail experience. Il limite è sempre la fantasia, basta che questa sia poi effettivamente supportata da una sufficiente conoscenza del dispositivo in questione per capire cosa è effettivamente realizzabile.
Diversi “esperti” di marketing si sono cimentati nello spiegare cosa è un iBeacon e voglio provarci anche io, dato che a tempo perso ci sto giochicchiando.

Read more!