NewFiveFour | Blog | Portfolio

Swift 3 and RxSwift: Wrapping a URLRequest in RxSwift.

Let’s assume we have request called r, let’s first create an Observable:

let ob:Observable<Something> = Observable.create { observer in
    let task = URLSession.shared.dataTask(with: r) { data, response, error in 

    return Disposables.create {
.subscribeOn(ConcurrentDispatchQueueScheduler(globalConcurrentQueueQOS: .background))

We’re starting the task in our observable, and returning a Disposable that simply cancels our task. And we’re subscribing the a scheduler suitable for background tasks, and observing in our main thread.

These are the bare bones of our RxSwift stuff, but we’re not actually doing anything with the task, we’re not returning either onNext or an error. Let’s do that:

if let e = error {
} else if let r = response as? HTTPURLResponse {
    if(r.statusCode >= 200 && r.statusCode < 300) {
        if let d = data {
            observer.onNext(Response(data: d, response: r))
        } else {
            observer.onNext(Response(data: Data(), response: r))
    } else {
        observer.onError(ResponseError(data: Data(), response: r))
} else {
    observer.onError(ResponseError(data: Data(), response: HTTPURLResponse()))

Firstly, we’re looking for an error, and if there’s one, we return that, otherwise if we have a response, we look at the status codes, and return as appropriate.

Response and ResponseError are simple data objects, and you probably want to do something with Observable.onComplete.

This is mostly stolen from here.

swift ios rxswift

Swift 3, Xcode 8 and iOS: UINavigationController basics

The UINavigationController allows you to navigate back to a view controller from child view controllers using a back button.

First create a UIViewController with a button. Then select this in the left hand side hierarchical pane, then click Editor in the window menu, Embed in and then choose Navigation Controller.

They’ll be a new UINavigationController, with a root view controller relationship link from that to your first view controller. They’ll be a styleable UINavigationBar within this UINavigationController.

Create another view controller, and control drag from the button you created button in your first view controller to this new view controller, to create a show action segue.

On starting the app, it will load the UINavigationController (or should do, depending how you’ve setup your app), which will the start the first view controller. From there, when you press the button it’ll load your third controller.

You should of course see a navigation bar at the top of each view. And when you get into the third view, you should see a back button you can use.

In your initial view controller, they’ll also be a UINavigationItem, which you can use to set the title of your view controller and the name of the back button used when coming back.

Also, at the same level as the view in the third view controller, you can add UINavigationItem and give that a title too. And in of your view controllers, unclicking Adjust scroll view insets may help if your content is being pushed down.

swift ios ios-navigationcontroller

Swift 3 and iOS: Segues

Let’s say you’ve control click dragged from a UIButton to another UIViewController in your storyboard. You’ve now created a segue.

Click on it, and in the attributes inspector tab, name its identifier segue1.

In your view controller from which you’re leaving for the new one, add this:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "segue1") {
        let detailVC = segue.destination as! SomeViewController;
        detailVC.someValue = "JOHN COLTRANE"

This says for the identifier segue1 which we named above, cast the UIViewController to SomeViewController, the name of our destination view controller.

Then set a property on that view controller, named simply via var someValue = "blar" for example in your destination controller.

Note, as soon as you have detailVC in the example above, the view controller will be initialised and visible on the screen.

ios swift

Swift 3 and iOS: UIPicker

In your view controller, use these delegates UIPickerViewDelegate, UIPickerViewDataSource. And implement the methods as follows:

public func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1

public func pickerView(_ pickerView: UIPickerView,
                       numberOfRowsInComponent component: Int) -> Int {
    return items.count

public func pickerView(_ pickerView: UIPickerView,
                       titleForRow row: Int,
                       forComponent component: Int) -> String? {
    return items[row]

The first method says the number of ‘components’ we have in each picker row. The second gives the items in our picker. And the final one gives the string for the ui picker. The items element here is a simple list in swift.

Finally add the picker to your storyboard, control drag it to the icon that represents the view controller, and make the view controller both the delegate and the data source for the picker.

If you want to detect when there’s a change in the picker, use this method in your view controller:

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    // Do something with the row
swift ios ios-uipicker

Swift 3 and iOS: Using a UITableView

First create a normal UIViewController. It could be a UITableViewController, but by using the UITableViewDataSource and UITableViewDelegate protocols we achieve the desired effect:

class ATableViewController : UIViewController, UITableViewDataSource, UITableViewDelegate {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 3

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)

        cell.textLabel?.text = "Section \(indexPath.section) Row \(indexPath.row)"

        return cell

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "Section \(section)"


The first method is the number of section headers in the table view. The second is the rows in each section. And the fourth returns the title for each of our three sections.

The third method says: “Get a named cell for the row we want”. We then give that some text and finally return that.

Next create a UIViewController in your storyboard. Give it a custom class as the one you just created above. Then to its view add a UITableView. Give that auto layout margins to match its parent if you’re using auto layout.

Within that UITableView add a UITableViewCell and give that a Restoration Identifier as LabelCell, as referenced above.

From this point, once you goto that controller, you should see your table view.

ios ios-uiviewtable swift

Page 1 of 70