Most of my days are spent in the wonderful world of .Net, Visual Studio, and the almighty Nuget Package Manager which is the C# no-hassle/couldn't-be-easier-to-use dependency manager. I'm emphasizing this for a reason. There's no silver bullet, any-dummy-could-do-it way of managing dependencies in Xcode.

Today I decided that I'd like to check out RxSwift for a side project I'm starting and I decided to use Apples own Swift Package Manager to manage my dependencies. I mean, its the future of dependency management, right? Maybe? In my opinion, SPM honestly needs a GUI interface like Nuget Package Manager to become widely adopted.... but that's neither here nor there.

Anyway, let's get to the point of this article... installing dependencies using Swift Package Manager.

Setup

Don't skip over this. I did and I wasted two hours because I made the assumption that by having Xcode installed that my tooling was properly setup, it wasn't.

Double-check that your Toolchains are indeed installed at `/Library/Developer/Toolchains`

Open terminal and execute the following command:

$ export TOOLCHAINS=swift

Sweet, now we're ready to rock.

Installing our dependency into a new project

This may not apply to many of us, so I'll cover installing into an existing project below. But, to install into a new project you create a new folder with your would-be projects name. Then navigate to the folder using Terminal. Let's assume I created a folder called `MyExampleProject` on my desktop. We'd navigate to the folder by typing this into Terminal:

$ cd Desktop/MyExampleProject/

Next we'll init our project using the following command.

$ swift package init

If all has gone well, your new folder should look like this:

Now, let's open up our Package.swift file to see what we've got.

// swift-tools-version:4.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "MyExampleProject",
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "MyExampleProject",
targets: ["MyExampleProject"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "MyExampleProject",
dependencies: []),
.testTarget(
name: "MyExampleProjectTests",
dependencies: ["MyExampleProject"]),
]
)

In order to import the RxSwift package, we'll need to add a dependency line item, which will look something like this:

The code above just points to the GitHub url and specifies exactly which version of the library we want. There's a couple of overloads for this package method available. You can take a look at the source code here to see your other options.

note that this file has changed slightly to accommodate our project name.

So, here's where I'm a bit unsure of the best way to do this so if you have any suggestions you get bonus points for correcting me here. My intuition says that we can use the command swift build to simply build our packages. However, this doesn't actually add RxSwift to our applications. By experimenting, I was able to get the RxSwift projects loaded by using the same swift package generate-xcodeproj command. So, yeah, back up your project files.

With that said, we'll once again execute the following command:

$ swift package generate-xcodeproj

Which, for me, installed the RxSwift project files into my project for me. My existing project now looks like this:

The last thing you'll need to do is edit click ManageScheme in the top left and add your app scheme back into the project.

Feel free to ask questions or offer corrections in the comments below. Thanks to @vzsg in the RxSwift Slack Community for his guidance.

Now, there are a couple of ways to install these libraries. You can use CocoaPods, which if you’re using the same point release of Xcode that the library was created with you should be alright, otherwise, you’re sure to be in for an untold quantity of build errors before you’re up and running. Alternatively, you could install the service as a framework provided it was compiled correctly for your current Xcode version. Or, you can do it the fool-proof way, and just include the Objective-C files into your application and add a bridging header.

(Dear Apple, please see Nuget Package Manager…)

This is my preferred approach because it's timeless. Doesn’t matter which version of Swift you are using or what version of Xcode you’re using. It just works.

So, assuming you’ve got an existing Xcode project and the Azure service you wish to install downloaded to your computer. We can get started.

In the downloaded folder, look for the Objective-C source code. In the case of Azure Storage Client Library, its a folder named after the service. So, find something like this:

Next, create a new Group in your Xcode project and name it whatever you like. I just named mine “Azure Storage”. Once you have the folder created, go ahead and drag all of the Objective-C files from the folder you downloaded to your new Xcode project folder. Select copy if needed and then “Finish”.

Xcode will then ask you if you want to create a bridging header for these Objective-C files, select “Create Bridging Header”, we’ll need this bridging header to expose Azure to our Swift code.

By default, Xcode will place that bridging header in with off of Azure’s Objective-C files, I personally move this file into my own project hierarchy since I might reuse this file to incorporate other Objective-C libraries.

If we choose to move it, we’ll need to inform Xcode where we moved it to. We can update our bridging header path by editing the location stored under Objective-C Bridging Header in our Build Settings.

Since I moved my bridging header into the main project hierarchy, I had to update my path to “AzureStorageExample/AzureStorageExample-Bridging-Header.h”

Once we have that updated, Xcode will, once again, be able to expose Azure’s Objective C code to our Swift code. Of course, this wouldn’t be a day in the life of an Xcode user if there wasn’t a follow-up error.

Looks like Azure has a dependency on `libxml/xmlwriter.h`, which is pretty simple to resolve. We’ll just have to tell Xcode where the file is.

We’ll go back into our build settings and select “All” and then “Levels” from our build settings and then search for “Search Paths”. Under header search paths, we’ll add a search path of “${SDKROOT}/usr/include/libxml2”.

If we rebuild we’ll get a gang of errors. We’ve got one last step here.

Extensions allow us to extend the functionality of the native Swift language with our own functionality.

I'd like to provide a real-world example where extending a specific type really reduces clutter in my applications. I often use the popular SWRevealViewController library to add a neat sidebar menu to my applications. Once I have the application setup, I have to run the following block of code in my viewDidLoad:

This actually gives us an error, because not every View Controller and Table View Controller use an SWRevealViewController, so that menuButton doesn't always exist! We need to constrain our extension to just those that actually derive from SWRevealViewController. In order to make this constraint possible, we need to define a protocol that will act as a contract or guarantee that our menuButton will indeed exist.

In this tutorial we go through the process of installing and setting up ReactiveUI 7 in Xamarin using the Model-View-View-Model pattern. Here, we'll take a high level look at all of the moving pieces we need in order to end up with an app that binds using ReactiveUI.

Installing ReactiveUI

We’ll begin by opening Visual Studio (or Xamarin studio) for mac. We’ll select `File->New Solution` and we’ll select Forms App. Click Next.Choose a name, we’ll target both Android and iOS, choose portable class library and I personally write my interfaces using C# but you can use XAML if that’s what you are comfortable with. We’ll move on to the next dialog and if we’re happy with were Visual Studio is saving our project, we’ll click create.

Expand your Xamarin forms project and right click on packages and select `Add Packages…` Once the package manager dialog appears, search for RectiveUI, select the version you want to work with and click Add Packages. Accept the subsequent agreements and your packages should install without a problem. Next, go ahead and install the reactiveui-xamforms package.

Once complete, double check that your packages look like this:

Noticed that the package manager has automatically added the Rx and Splat dependences along with reactiveui and reactiveui-core.

Next, we’ll go ahead and add ReactiveUI to both our .Droid and .iOS projects as well. These steps are the same as with the forms project.

Just make sure that all of your package versions are exactly the same.

ReactiveUI Base Classes

Now that we have ReactiveUI installed we’ll set up our project using the MVVM pattern.

We’ll begin by adding two folders to our Xamarin Forms application. We’ll create a folder for our ContentPages, which we’ll call UserInterfaces and one for our ViewModels which we’ll call ViewModels. Once complete, your solution should look something like this.

Next, we’ll add a pair of base classes. While this step isn’t necessary to use ReactiveUI, it does enforce a predictable pattern across our documents making them easier to work with over time.

We’ll start by right clicking on our ViewModels and we’ll select add file. We’ll create a new C# file which we’ll name ViewModelBase. Next we’ll add the following code.

This is a minimal version of a ViewModelBase class implementation that I learned from the mobile development experts at Eight Bot. This version, of course, is drastically stripped down compared to what one might use in production. But it will get us up and running for this exercise.

Let's take a high level look at what's going on here.

We have an abstract class named ViewModelBase that offered a generic parameter. In ReactiveUI, all view model base classes must inherit from ReactiveObject, we are also implementing IDisposable. Finally, we're explicitly stating that our generic `T` parameter must implement both ReactiveObject and IDisposable.

We’ve created a Lazy CompositeDisposable named ViewModelBindings. We’ll use this property to collect our ViewModels disposable subscriptions which get cleared out when our pages Dispose override method gets called. To learn more about CompositeDisposable check out the Introduction to Rx page on Disposables.

We’re employing a boolean flag named IsDisposed to keep track of whether our objects have been disposed. This will keep us safe from disposing of an object more than once.

RegisterObservables is an abstract method that we'll use to register our observables in our view model.

Finally we take care of our disposables. This should be familiar to those who have spent any time using .Net. You can learn more about IDisposable here[3]

That does it for our ViewModelBase class. Once again, this is a simple version of what one might use in production but it is by no means production ready. Let’s go ahead and wire up a ContentPage base class using ReactiveUI.

Right click on your UserInterfaces folder and add a new C# file named ContentPageBase. Next, we’ll add the following code to out new file.

ReactiveUI in Action

Now we have everything we need to wire up a simple interface. We’ll begin by adding a new class which we’ll name `Dashboard.cs` to our ViewModels folder. Once our document has loaded we’ll make sure that our namespace to reflect our folder hierarchy to avoid collisions.

namespace YourAppName.ViewModels

We’ll inherit from our newly created ViewModelBase class and simply pass our Dashboard class type in as our type specifier. At this point Visual Studio will require that we implement our abstract base class, which is what we’ll do.

Before we move on, I want to point out that the goal of this exercise it for you to get up and running with ReactiveUI and MVVM. So I’ll forgo any in-depth explanation of the moving pieces you’re about to see. If you have any questions feel free to leave them in the comments section below.

We’ll take a high level look at whats going on but we’ll spare the detail.

We’ve included several properties that we’ll bind to in our Dashboard ContentPage.

We’re including a status message which is of type string, current image which is a Xamarin Forms ImageSource, a List of strings that will hold a list of image names and title which is of type string.

We’re including a ReactiveCommand which we’ll bind to in our ContentPage later.

Next we have our RegisterObservables method which, if you recall from our base class implementation, gets called from our constructor.

Here we have our ReactiveCommand implementation. When our command gets fired from our ContentPage, this is the logic that will execute.

Finally, we have a Reactive observable that fires every have second and binds a random image to our CurrentImage property.

Important: In order for your application to run, you’ll need to add images to both your iOS and Droid projects respectful resource folders. If you are at a shortage of images, you can use the ones that I’ve included in this project by downloading them from my example project here.[4]

Alright, we’re almost there! Let’s finish up by adding a content page to our app. We’ll right click on our UserInterfaces folder and add another file named Dashboard.cs. Hopefully you remembered to change your namespace earlier or you’ll be sure to confuse the compiler.

The first thing we’ll do is inherit from our ContentPageBase and then we’ll pass in our view model dashboard type. The rest of the code for this demo, goes something like this:

And here is where the magic happens… We’re using three different binding statements to bind our interface controls to observables in our view model.

So, your code should be complaining right now since DisposeWith doesn’t actually exist in ReactiveUI! This is an extension method provided by Eight Bot in their public GitHub repository on Reactive-Extension, which you can find here.

Create a new folder in your application named Extensions and add a new class named IObservableExtensions. Add the following code.

This tutorial is part of a series on iso-charts, if you haven't looked over the introduction I'd advise doing so before continuing. In this tutorial, we'll be making a combined chart using iOS-charts.

We’ll begin by creating a new single view application, we’ll name it and click create.

Go to the main.storyboard and search for “View” in the Object Library and you’ll see it near the bottom of the list. Drag the view out onto your view controller, position it however you like and add some basic constraints.

In the identity inspector, set the class for your new View to “CombinedChartView”, if you aren’t seeing an option for such a class please make sure you’ve followed the installation steps listed here.

If everything has gone well your main.storyboard should look like this:

Setting up our CombinedChartView object

Click on your Assistant Editor to reveal your ViewController.swift code. We’ll need to add an import statement and adopt a protocol before we can begin wiring up our Line Chart. Modify your class signature to look like this:

Here we set up our CombinedChartData adding both lineData and bar Data.

Add our data to the chartView.

animate our chart.

Next, we'll define our two function we used to set our lineData and our barData:

func setLineData() { }
func setBarData() { }

For this part of the tutorial, we'll set each chart up with two sets of data, which will create a single red line across our graph. I won't go into detail here because as you read through you'll get a good idea of what the properties mean.

This tutorial is part of a series on iso-charts, if you haven't looked over the introduction I'd advise doing so before continuing. In this tutorial we'll be making a single line Line Chart using iOS-charts.

We’ll begin by creating a new single view application, we’ll name it and click create.

Go to the main.storyboard and search for “View” in the Object Library and you’ll see it near the bottom of the list. Drag the view out onto your view controller, position it however you like and add some basic constraints.

In the identity inspector, set your class to “LineChartView”, if you aren’t seeing an option for such a class please make sure you’ve followed the installation steps listed here.

If everything has gone well your main.storyboard should look like this:

Setting up our LineChartView object

Click on your Assistant Editor to reveal your ViewController.swift code. We’ll need to add an import statement and adopt a protocol before we can begin wiring up our Line Chart. Modify your class signature to look like this:

Finally, we call / create a custom function that will add data to our chart.

Setting Data

Of course, a very common thing to chart is money over time, and that what we’ll do in this example. So we’ll modify the signature of our setChartData method call to take an array of strings for our months.

We start by creating an array of ChartDataEntry items, to which we'll create and append one item for every value stored in our dollars array.

We create a LineChartDataSet that take our array as its first parameter and a label for its second, this dataset represents the line we'll be creating. We continue by setting the attributes that belong to this class object.

Since we're ultimately on a path to create a multi-lined array, we'll create a data set array that will just hold our single set.

Create a data object that takes our months and our single data set.

Set it as our lineCharView objects data

Build and run

Build and run and you should see your first chart, congratulations, it gets better from here so move on to part II, where we augment this chart with multiple lines.

Delegates are the standard way we pass data between two view controllers. I recently wrote a tutorial on how to pass data by overriding prepareForSegue. In this tutorial I’ll show you how to pass messages back and forth using the “Standard” protocol pattern and without using any segues.

There won’t be an in-depth discussion about protocols or delegates here, for that I defer to Apples Swift Programming Language Guide or one of the many excellent books or online resources that have already covered this topic ad nauseam.

What I will do, is create a succinct-minimal-working delegate pattern example, using naming conventions that will make it clear how the delegate pattern works.

Setting Up

We’ll start by creating a single view application.

We’ll add a second View Controller to our storyboard which we’ll need to create a new CocoaTouch file for. We’ll do that by clicking add new > cocoa touch class > find UITableViewController… name it PresentedTableViewController and create.

This controller class will belong to our “presented” view controller, so make sure you add it in your storyboard. Your final storyboard should look like this:

In the first View Controller, lets add a button and a label. We don’t need anything fancy for this exercise, just slap em out there. With split view open, control drag an outlet from your label and name it labelOutlet, and control drag an action from your button and name it doPresent. You should now have something like this:

Now, select the other View Controller, the PresentedViewController and add a Text Field and a Button to the View. Just as before, control drag from your Text Field and create an outlet named “textFieldOutlet” and repeat that for your button, this time making an action named “doDismiss”. Your code should look like this:

The convention is to adopt the presented classes name with “Delegate” afterwords. Inside our protocol we’ve defined one function, acceptData that takes AnyObject. I should note that we can define any number of functions and properties inside of our protocol, but no logic.

Think of a protocol as a binding contract between the protocol and any class that implements it. This contract forces said classes to abide by it's "protocol" and in doing so creates a level of "trust" from the compiler. This "trust" enables us to communicate between two separate bodies of code.

PresentedViewController

We’ll add the required code necessary to receive data from the view controller, but this wont be a one way dialogue. We’ll wire this up so it will send data back to the View Controller as well.

At the class level, add two properties. One being a variable called delegate with a type PresentedViewControllerDellegate. Which will look like this:

We’ll proceed with our protocol implementation by adding its acceptData(data:AnyObject!) method, which silences the compiler. Inside that method we’ll simply update our text label with the message we entered in PresentedViewController.

Finally, we’ll address the doPresent action we created earlier. Since in this exercise we aren’t passing values via Segue, we’ll need a method of traversing our data. In this case, it’s by presenting the view controller. We’ll create an instance of our PresentedViewController and with that instance, we can bind to it properties before presenting. That code looks like this:

Build And Run

When click the next button you should see the next view controller along with a print line in your console. If you enter some text in the text field and hit your go back button, you’ll see the text you entered assigned to you label.

If you have any troubles, feel free to download the Project Files and browse my code. You can also ask questions in the comments and we’ll get your code running.

Before we move on, click on your prototype cell in your storyboard and give it an Identifier of "Cell" and give it a Style of Basic for this example.

Now that we have our main controller lets add a View Controller that we'll send our values to. Drag a View Controller our onto your storyboard just as we did for our Navigation Controller. And just as we did with our FirstTableViewController, we'll add another Cocoa Touch Class, this time uses a UIViewController and we'll name it SecondViewController. Remember to add your new class to your View Controller in your storyboard as we did before for our FirstViewController.

Finally, we'll create a segue by control dragging from our FirstTableViewController to our SecondViewController like so.

Click on your new segue and in your Attributes Inspector add an Identifier, I chose "SendDataSegue" for this example.

We'll also want to add a label to our new View Controller, place it dead center and give it some simple constraints. Finally, create an outlet in your SecondViewController.swift by control dragging from your outlet to your class.

Name your outlet viaSegueLabel, it should look like this:

@IBOutlet weak var viaSegueLabel: UILabel!

Code

Open your SecondViewController and at the class level, add a property called viaSegue like this:

var viaSegue = ""

Then inside your view controller we'll assign the value of viaSegue to our viaSegueLabel, add the following code to your viewDidLoad:

Now, let's add a method called prepareForSegue, which does exactly what it sounds like it does, it prepares for the upcoming segues. To learn more about prepareForSegue see Apples Developer Guide. Here's the implementation:

In this method, we're determining which segue we're preparing for with segue.identifier, we're then using an if let to safely attempt to assign a segue with a destinationViewController with a type of ours. Getting the type lets us model the properties within, thus giving us access to our viaSegue in our SecondViewController, which we take advantage of here.

We haven't actually set up a segue yet, we'll do that now. Lets add a new tableView override function for didSelectRowAtIndexPath, this will allow us to trigger a segue from whichever row we select. The implementation is simple so I'll stop rambling.

What is CocoaPods?

"CocoaPods manages library dependencies for your Xcode projects.

The dependencies for your projects are specified in a single text file called a Podfile. CocoaPods will resolve dependencies between libraries, fetch the resulting source code, then link it together in an Xcode workspace to build your project.

Ultimately the goal is to improve discoverability of, and engagement in, third party open-source libraries by creating a more centralised ecosystem."

Setting Up

We'll start by creating a new ASP.NET MVC 5 project and we'll make sure we have individual accounts selected. We're doing this so that we get entity framework and our dbcontext out-of-the-box.

In your new project, let's create two models. We'll make a Page model and a MetaViewModel. The Page model will contain all of the properties that we'll be using in our database, the MetaViewModel will be used to shape the data for rendering our partial view. This will make perfect sense when you see it in context.

Adding Models

So let's create our Page.cs file in our model's folder and then we'll add the following code:

We'll need a Partial View

Notice that we're returning a partial view in this method, obviously that doesn't exist yet, so we'll need to make that now. Right click on your "ListMeta" method and select Add View. A dialog window will appear, make sure you fill it out just as I've done below.

Once your new partial view is created lets replace the code with the following:

Now, lets open our _Layout.cshtml, which acts as a template for all of our future Pages and we'll add the following line inside our <head> tags:

@RenderSection("metatags", false)

Alright, we're ready to create our database!

Open your package manager console window by selecting view > other windows > package manager console. Once your console has opened we're going to run the following three commands individually.

enable-migrations

add-migration initial

update-database

If everything was successful, you now have a local database which will serve nicely for our example.

Build and Run

Finally, lets build and run our project. Once your project compiles and the browser opens. Navigate to the following URL:

localhost:{port}/pages/create

You'll see a create form, fill it out and click create. You've just created a "Page" that contains your specified meta data. After your record posts, you'll see a new screen with the results. Click the "details" link and you'll be taken to the details page.

Right-click and choose "View Source" and you should see your specified source as I've shown below

That's it... If you have any problems just leave a comment and I'll try to clarify for you.