Category Archives: Swift

Setting up Ubuntu – Getting Ready for Server Side Swift

So this is going to be a quick step by step tutorial on the steps that I took setting up Ubuntu inside of VirtualBox on my Macbook Pro. Before we get started make sure you have VirtualBox Installed.

You can get a copy here.

While you are installing VirtualBox you will want to download a version of Ubuntu that you can use in your configuration. I wanted a graphical desktop so I downloaded Ubuntu Desktop which you can get here.

As just a personal preference I store my ISO images in a folder that is easily accessible from the desktop. Your choice on where you put it just make sure it’s somewhere easy for you to get to.

Setup

With VirtualBox installed and your ISO image for Ubuntu downloaded let’s get started. Go ahead and start VirtualBox.

Create a new Virtual Machine by clicking on the New button.

Screen Shot 2016-08-25 at 10.22.01 PM

Name Virtual Machine

Next you will want to setup and name your virtual machine. For this example I took the name directly from the name of the ISO image downloaded ubuntu-16.04.1-desktop and use that as the name. Once I set my name the Type (Linux) and Version (Ubuntu (64 bit version)) were automatically updated.

Screen Shot 2016-08-25 at 10.32.36 PM

Memory Configuration

Your ability to configure memory for your virtual machine will be limited by your machines physical configurations. I am fortune enough to have a lot of memory installed on my MacBook Pro.

On the Ubuntu configuration page it recommends 2 GB of system memory so to play it safe I doubled that number to 4 GB.

Screen Shot 2016-08-25 at 10.38.11 PM

Setting up Disk

I already know that I want to do some development on this image so I made the decision to give it more disk space for future development.

In my configuration I am going to create a 100 GB Fixed size VirtualBox Disk Drive.

Screen Shot 2016-08-25 at 10.45.17 PM

Screen Shot 2016-08-25 at 10.46.09 PM

Screen Shot 2016-08-25 at 10.46.59 PM

Screen Shot 2016-08-25 at 10.48.03 PM

Start your Virtual Machine

With the VirtualBox all setup and ready to run it’s now time to get Ubuntu running. Select the image that you just created and the click the Start button.

Screen Shot 2016-08-25 at 10.22.01 PM

It’s first question will be to prompt you for a optical disk image to use for installing Ubuntu. You will want to browse to wherever you downloaded Ubuntu and select it.

Screen Shot 2016-08-25 at 11.00.08 PM

Some message and error prompts that may come up that you can either clear or click the OK button on to get rid of.

Screen Shot 2016-08-25 at 11.01.06 PM

Screen Shot 2016-08-25 at 11.02.56 PM

Install Ubuntu

These next few screens are steps that I took for my configuration. Review them during your installation and make any adjustments that are appropriate for your preferences.

On the first screen you will of course want to click on Install Ubuntu.

Screen Shot 2016-08-25 at 11.05.37 PM

Screen Shot 2016-08-25 at 11.07.11 PM

Screen Shot 2016-08-25 at 11.08.01 PM

Click Continue

Screen Shot 2016-08-25 at 11.08.53 PM

Screen Shot 2016-08-25 at 11.09.59 PM

Screen Shot 2016-08-25 at 11.10.58 PM

Screen Shot 2016-08-25 at 11.12.35 PM

When you are all finished with the installation it will prompt you for restarting your machine. As just a reminder it is referring to the Virtual Machine that was created earlier.

Click the Restart Now button.

Screen Shot 2016-08-25 at 11.15.15 PM

When it prompts you to remove the install media just click the Ok button to proceed. All that is left now is to login and enjoy.

Screen Shot 2016-08-25 at 11.19.26 PM

Done

With Ubuntu running we are now ready to start on the next step of installing Swift 3 and getting ready to start using Vapor. That will come in a future post and for now check out Ubuntu and get comfortable with it.

Screen Shot 2016-08-25 at 11.23.33 PM

Keep following and as always Happy Coding.

Catching the Bug… Server Side Swift

In my opinion Swift is an extremely exciting and powerful language so like many others I was excited when I heard Apple’s decision to Open Source Swift and even more when a Linux compatible version of Swift was released. Writing apps for different platforms with Swift sounded exciting but what immediately started running through my mind was the ability to do server side development with Swift much like I have done with Javascript, Java and C#.

I started to review the different options available and I finally decided to take the next step of going from reading/dreaming about the possibilities to actually doing something. It turns out that I have the perfect opportunity as my website for DooScrib was taken offline and I would like to bring it back online (future updates to the plugin planned).

The following is the environment that I have chosen:

Server Side Frameworks

There are actually several choices out there and as time progressed I narrowed down the options that I was most interested in to the following:

Kitura is great and has a lot of information as well as the security of have a big name like IBM behind it. However as a personal preference I automatically gravitated towards Perfect and Vapor and have been watching both as they have progressed over the last few months.

To be honest I think both Perfect and Vapor are great choices. At a later time I might actually even pursue a separate review of Perfect.

Getting Started

So for those interested in following I plan to write several different posts over the next few weeks as I setup a Virtual Machine running Ubuntu, install and get Swift running and finally begin working with Vapor.

Keep following and as always Happy Coding.

Protocols and Delegates and Swift, oh My!

Many years ago when I was learning Objective-C my initial impression of protocols and delegates was one of confusion. When I first started reading and learning about them and their idea I was expecting something hard to totally comprehend and most likely difficult to implement.

Very shortly however I began to realize that it was neither.

Protocols

I think that Apple gives a great description for a protocol.

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.

A more simple example (non programming) of protocols is the process of building a house.

You start first with the creation of a set of architectural drawings that are printed (blueprints) and distributed to the various contractors whose responsibility is to create an implementation. Think of protocols as the architects printed blueprints and the implementation of them as the actual house being constructed.

Back to the programming world, and for those that are new to Swift, think of protocols as abstract interfaces which allow you define an interface to be used in the construction of an object.

Delegates

The process of delegation allows you (the delegator) to notify another object or hand over work to another object (the delegate) which has an interest in your execution. In my opinion you will see it used most often as a form of notification from one object to another.

For the MVC purists that are out there you will most likely be familiar to delegates as the Observer Pattern that glues everything together.

Putting it All Together

In the sample application I am going to demonstrate how you can use a protocol to implement functions used for the purposes of notification as well as how to use them to get information from the delegate.

In the application there will be a button that when clicked runs an asynchronous function which will repeat a unit of work based on a counter. To create some delay and simulate that each unit of work is actually doing something I added a sleep call for one second.

While the asynchronous function is running I want it to do the following:

  • Notify when work has started
  • Ask the delegate how many units of work it should execute
  • Notify when work has completed
  • Optionally I would like for it to update me as each unit of work is complete.

Let’s get started.

Create Project

Start off with creating a Single View Application:

Screen Shot 2015-10-29 at 6.47.57 PM

Screen Shot 2016-02-23 at 4.12.45 PM

Layout Screen

With the project setup complete click on the projects storyboard (Main.storyboard) and add a Label for a status that will get displayed and a button labeled Run Work.

Screen Shot 2016-03-02 at 5.36.51 PM

Once you have added those fields and the constraints in place go ahead and give it a test run in the simulator.

Screen Shot 2016-03-02 at 5.41.22 PM

With the storyboard editor still open click on the Assistant Editor so that both the storyboard and ViewController.swift are displayed.

Screen Shot 2015-02-26 at 11.00.34 PM

Then control drag and create a property for the Label as well as a function to handle Run Work button when it is clicked.

    @IBOutlet weak var labelWorkStatus: UILabel!

    @IBAction func runWork(sender: AnyObject) {
    }

After that is done you can close the Assistant Editor and you will now begin to work on the code.

Create the Protocol

Next you will want to add a new file for the protocol.

Screen Shot 2015-10-30 at 4.04.26 PM

A basic protocol would be defined as follows:

protocol ProtoExample {
    // add your definitions here
}

Here is the code that you will want to paste for the protocol that will be implemented. There are be a couple of parts to this that are different from the normal that I will explain.

@objc protocol ProtoExample {
    var workTime : UInt32 { get }
    
    func workIsStarting()
    func workIsComplete()
    
    optional func workInProgress()
}

Protocol definitions are fairly straightforward when you look at them. You basically define the layout of the function that you expect to be implemented much like you would in any other class. The exception of course is that you don’t supply an implementation.

When dealing with properties you have to make sure that you define them with a var in the front and then follow them with their access method (get set). If you wanted to create a property with a get and set access it would look like the following:

    var workTime : UInt32 { get set }

What about that @objc that I added to the front of the protocol definition?

In the requirements I discussed the option of getting notifications as the work progresses. In order to achieve this I marked the workInProgress function as optional meaning that the implementor of the protocol would not be required to implement this. In order to make use of this keyword you have to also mark your protocol with @objc.

Adding this attribute doesn’t require you to now use Objective-C in your development. The only downside that comes from marking the protocol this way is that it means only class objects can inherit from your protocol.

You can get more information about the @objc attribute here.

Create the Model

Next you will want to create the model which will implement the asynchronous function as well as use the delegate the protocol was designed for.

Screen Shot 2015-10-30 at 4.04.26 PM

The requirements for the model are simple so lets just create an asynchronous function that makes use of the protocol. I am not going to go into the details of queues and asynchronous programming but for those that want more information you can read a great article about asynchronous operations for iOS here.

class ProtoModel {
    var delegate : ProtoExample?
    
    func doSomeProcessing() {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
            // let them know that we are starting
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.delegate?.workIsStarting()
            })
        
            // do some stuff
            var workTime : UInt32 = 0
            if let del = self.delegate {
                workTime = del.workTime
            }
            
            while 0 < workTime { sleep(1) dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    self.delegate?.workInProgress?()
                })

                workTime--
            }

            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.delegate?.workIsComplete()
            })
        })
    }
}

In this example the delegate is not mandatory for execution. I did this intentionally to demonstrate how the delegate would be used in the common scenarios where users may not be interested in the notifications.

If you wanted to make the delegate a requirement then you would change the code to look more like the following:

class ProtoModel {
    var delegate : ProtoExample
    
    init (delegate: ProtoExample) {
        self.delegate = delegate
    }
    
    func doSomeProcessing() {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
            // let them know that we are starting
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.delegate.workIsStarting()
            })
        
            // do some stuff
            var workTime = self.delegate.workTime
            
            while 0 < workTime { sleep(1) dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    self.delegate.workInProgress?()
                })

                workTime--
            }

            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.delegate.workIsComplete()
            })
        })
    }
}

A couple of simple things to notice is that the property is no longer marked as optional and with that comes the requirement of the init constructor. Also notice how the calls using the delegate have changed.

But wait the signature to the workInProgress still has the optional tag. This is because if you recall the function was flagged with the optional keyword.

Implementing the Protocol

To implement the protocol open the ViewController.swift and make the required changes so that it inherits from and implements the protocol.

In this example you can make note that the optional function we defined is not being used. This is allowed because of the optional attribute we assigned to the function.

class ViewController: UIViewController, ProtoExample {
    
    @IBOutlet weak var labelWorkStatus: UILabel!
    
    // implement the protocol
    var workTime : UInt32 { return 10 }

    func workIsComplete() {
        labelWorkStatus.text = "Work is Complete"
    }
    
    func workIsStarting() {
        labelWorkStatus.text = "Work is Starting"
    }

Add the model as an optional property and make sure that it is created in the viewDidLoad function.

    var protoModel : ProtoModel?

    override func viewDidLoad() {
        super.viewDidLoad()

        // create and setup the model
        self.protoModel = ProtoModel()
        self.protoModel?.delegate = self
        
        // setup the view
        labelWorkStatus.text = "Ready for Work"
    }

Finally change the handler for when the button gets clicked so that it will call the asynchronous function doSomeProcessing created in the model.

    @IBAction func runWork(sender: AnyObject) {
        if let model = self.protoModel {
            labelWorkStatus.text = "Work is requested"
            model.doSomeProcessing()
        }
    }

With all that complete go ahead and run the application, click the button and you should see the status being updated as the function doSomeProcessing progresses.

For now you can get complete the source here and as always Happy Coding!!!