Working easily with location in iOS8 and Swift with OneShotLocationManager

Since CLLocationManager doesn’t support block based APIs sometimes it’s very annoying to setup a delegate and implement all delegate methods if you just want to fetch the current location once and that’s it.

OneShotLocationManager is a class that solves that problem in Swift. Whenever you need to fetch the current device location you just need to create an instance of OneShotLocationManager and call the method to fetch a location. It will request the necessary authorizations and return the current location. Very easy. It just works.

Using OneShotLocationManager is really very easy since it’s supposed to do just one thing – fetch the current location and give it to you.

Let’s have a look at how to use it in a sample app.

Creating an Xcode 6 app that uses location

Using location in iOS8 works a bit different compared to how it used to work in iOS7 and earlier. It’s not much different in the end and it actually boils down to these few changes:

  • you need to ask for specific permission – either to use location when the app is in the foreground only, or always – i.e. in foreground and background
  • you need to add to your Info.plist a description what do you need the location for
  • once you get the proper authorization from the user you work with CLLocationManager as usual

So let’s create an Xcode6 app and configure it to work with location data.

Open Xcode and from the main menu select File/New/Project…, select the iOS/Application/Single View Application project template and click Next. Call the project LocationDemo, make sure the selected Language is Swift and click Next.

Finally save the project somewhere on your disc. Now you have the empty project ready. In this project you are just going to fetch the current location so you won’t add any UI to the storyboard.

Now let’s add the location permission description that the app will use to ask the user for authorization.

Select the project file LocationDemo in the File Navigator, then make sure the proper project target is selected – LocationDemo, and then select the Info tab.

xcode_infotab

Here you need to add the extra key for the location permission description. Hover with the mouse over the first item and in a second a “+” and “-” buttons will appear. Click the “+” button to add a new item in the Info.plist file.

infotab_addbutton

As name of the new item enter “NSLocationWhenInUseUsageDescription” and as value enter the text “We need to know your location to show you the coordinates where you are located“. In your real apps you need to be more informative why do you need the location information but for the this demo app this will have to suffice.

infotab_locationkey

Okay, that’s a wrap with setting up the Xcode project. Now let’s grab OneShotLocationManager from GitHub and add it to your project.

Import OneShotLocationManager

At the moment of this writing ther’s no better way of distributing Swift libraries but just copying over the source code to your project – so let’s do exactly that. Open the GitHub repository page of OneShotLocationManager https://github.com/icanzilb/OneShotLocationManager and to the bottom right find and click the button saying Download ZIP.

oneshot_github

From the unarchived folder grab OneShotLocationManager.swift and drag it into your Xcode project. When asked check “Copy items if needed” to include the source file in your own Xcode project and click Finish.

You’re now ready to use the class.

Easily fetching the location via OneShotLocationManager

You’re finally to write some code.

Open ViewController.swift from your Xcode project. We are going to add the location code in the view controller – just to learn how to use the class. In your own apps you can put this code whenever your app architecture requires you to.

First add a new variable to the class (add it just under the line where you declare the ViewController class):

This is the variable you will use to keep an instance of the manager while it fetches the location for you. Now you are going to add a new method to fire just after the view controller shows up its view on screen:

Your first task, of course, is to create a new instance of the location manager. Add at the end of viewDidAppear:

First you create a new OneShotLocationManager instance and then you call fetchWithCompletion on it. fetchWithCompletion will check the location permission authorization status and if you have never granted this app location permissions will ask the user for permissions. Once permissions are granted will fetch the current location and invoke the given code closure.

The two parameters, as their names suggest, will give you the current location or the error that arised when the class tried to fetch a location.

Now let’s add some code inside the closure to handle the response:

Inside the closure you try to unwrap the first parameter (location itself is an Optional – CLLocation?) – if the unwrap succeeds the operation was successful and you can use the location constant. Otherwise you try to unwrap the error parameter which is of type NSError? and see what kind of error you have on your hands.

You can check the code property on the error object for more details. If you look into OneShotLocationManager you can see some of the errors that you might get defined in the OneShotLocationManagerErrors enumeration:

Okay – one last step. Immediately after you have received result from the location manager, no matter if it’s an error or a location, you don’t need the OneShotLocationManager instance anymore – you can’t use it to try fetching a location second time.

So, still inside the closure, get rid of the manager instance:

In case you are using the iPhone Simulator to test this app you need to tell Xcode to simulate some location data for you. From Xcode main menu select Product/Scheme/Edit Scheme.

In the Edit Scheme dialogue do the following:

  1. Make sure Run is selected on the left
  2. Then check the checkbox saying Allow Location Simulation
  3. Choose as Default Location Tokyo, Japan

xcode_simlocation

Okay – all done! Build and run the the project. In the alert that pops up immediately after you start the app you can see the text you set in Info.plist:

alert_location_auth

Click Allow and check the Output Console in Xcode you should see the location object printed like so:

console_location

Success!

Where to go from here?

You can download the completed project here.

If you want to learn more about working with location data in iOS8 with Swift you should check out my colleagues’ new book called iOS8 by Tutorials.

In case you want to learn more about Swift – I recommend Swift by Tutorials.

And if you want them both and more, they have also a book bundle about Swift and iOS8 which gives you a discount on the book prices.

banner_380x200

And don’t forget this whole month is the iOS8 Feast on raywenderlich.com – we have a contest running and a prize pool of more than $10,000 value! You can participate with a single tweet too. Check out the iOS8 Feast – look for the tweet button.


Book: Swift by Tutorials

By the renowned authors from the ray wenderlich tutorial team – Colin Eberhardt and Matt Galloway comes the definitive introduction to Apple’s new programming language – Swift by Tutorials.

A brand new book which comes out synchronously with the official release of iOS8 and teaches you everything Swift.

Learning Swift is quick and easy – just follow the step by step tutorials to understand Swift’s data types, structures, and not only how things work, but also why do you need to program stuff to happen in a certain way and not another.

Swift by Tutorials is a part of a 3 books bundle, all written by the fantastic authors from the ray wenderlich tutorial team, which teaches everything about iOS8 and Swift. The bundle includes Swift by Tutorials, iOS8 by Tutorials, and Core Data by Tutorials. All books covering the latest tech: iOS8 APIs, Xcode 6, and Swift.

To learn more about Swift by Tutorials and the book bundle visit this page: www.ios8-by-tutorials.com

Or click this banner and go straight to the book store to buy instantly the 3 book bundle:

banner_380x200


It seems everybody is in love with Swift, but since Optinals are a rather advanced concept the Swift code I see published on the Internet tends to rather randomly unwrap Optionals. And to be honest I haven’t seen a good blog post to clearly explain in plain text when to unwrap in what way. So I thought I’d write one today.

So let’s start by a quick review what Optionals are.

What are Optionals

Consider your plain old data types just as the one you used in your Objective-C (or PHP, Javascript, etc.) code. Let’s say you have two variables called age and height. They are of the simple type Int and can hold any integer number. Let’s see a quick code sample:

You declare a variable age by using the keyword var and assign the value 35. You might change your mind later on and assign another value, say 36, and do that again and again. height on the other side is a constant – once you assign the value 100 to it – that’s it!

In both cases however you know that Int contains a value – an integer number. What you cannot do is to assign nothing to that variable – nil.

For example if those pieces of data represent an employee profile in a company database, for some records you might not know the height of the employee – in that case you shouldn’t set a value of 0 – you really should rather set the value to nothing or missing.

The case above would be a case where you would like to use an Optional data type.

Optional in fact, what many people don’t realize, is just an enumeration defined in Swift’s standard library and topped with some syntax sugar. The enumeration looks like this (abbreviated):

So Optional can either contain None – and since Optional is NilLiteralConvertible you can guess that that’s the case for when you want to use nil for an Optional value. The latter case defines that Optional can hold a value of type T – any type T you’d like.

So for an Optional<Int> – it can contain either nil or the Int value. Very simple and easy. So let’s use Swift’s syntax sugar ? and declare age and height variables that can hold and integer number or a nil.

By adding a ? immediately after the data type you tell the compiler that the variable might contain a number or not. Neat! Notice that it doesn’t really make sense to define Optional constants – you can set their value only once and therefore you would be able to say whether their value will be nil or not.

To make it crystal clear what’s going on when you use Optionals let’s look at what’s going on behind the scenes in the above example. The line:

is actually equivalent to:

It looks very easy once you know what’s going on there, right? The ? symbol you add to datatypes to declare them as Optinal is just syntax sugar that does translates into the code above.

Okay, now that I hope you have a good idea what an Optional data type is, let’s have a look at how to use those types in code.

When to use ? and when !

Let’s imagine you have a simple iPhone app – a UIKit based application. You have some code in your view controller and you want to present a new view controller on screen on top of your existing one. You decide to push the new one on screen via a navigation controller.

As you, hopefully, know every ViewController instance has a property navigationController. If you are building a navigation controller based app this property of your app’s master view controller is set automatically and you can use it to push or pop view controllers. If you use a single app project template – there won’t be a navigation controller created automatically for you, so your app’s default view controller will not have anything stored in the navigationController property.

I’m sure you already guessed that this is exactly a case for an Optional datatype. If you check UIViewController you will see that the property is defined as:

So let’s go back to our use case. If you know for a fact that your view controller will always have a navigation controller you can go ahead and force unwrap it:

When you put a ! behind the property name you tell the compiler I don’t care that this property is optional, I know that when this code executes there always will be a value store so treat this Optional like a normal datatype. Well isn’t that nice? What would happen though if there isn’t a navigation controller to your view controller? If you suggestion that there always will be a value stored in navigationController was wrong? Your app will crash. Simple and ugly as that.

So, use ! only if you are 101% sure that this is safe.

How about if you aren’t sure that there always will be a navigation controller? Then you can use ? instead of a !:

What the ? behind the property name tells the compiler is I don’t know whether this property contains nil or a value, so: if it has value use it, and oterwise just consider the whole expression nil. Effectively the ? allows you to use that property just in the case there is a navigation controller. No if checks of any kind or castings of any sort. This syntax is perfect when you don’t care whether you have a navigation controller or not, and want to do something only if there is.

Perfect! But how about if you want to do somethinge else in case there wasn’t a navigationController? For example show an alert box to tell the user something.

Then you would use an if let expression.

When to use “if let”?

if let is a special structure in Swift that allows you to check if an Optional holds a value, and in case it does – do something with the unwrapped value. Let’s have a look:

The if let structure unwraps controller.navigationController (i.e. checks if there’s a value stored and takes that value) and stores its value in the nav constant. You can use nav inside the first branch of the if. Notice that inside the if you don’t need to use ? or ! anymore. It’s important to realize that nav is actually of type UINavigationController that’s not an Optional type so you can use its value directly. (If you remember in contrast the navigationController’s original type is UINavigationController?)

if let is useful also in another case. Imagine that instead of a single method call you want to do more stuff with your navigationController. If you do not use if let you code will looke like this:

This code works but you need to unwrap the property 4 times and the code gets quite repetitive. It’s much cleaner and nicer (and faster) to unwrap the value once in an if let:

Much nicer, isn’t it?

One final note – nav in the above example is a constant. You can change properties on it and call methods, but you can’t change the value of nav. It’s worth mentioning that you can do something like that by simply using if var. It works the same way, but instead of an unwrapped constant you have an unwrapped variable and you could change its value if you wanted to so.

This brings us to the final use case I wanted to cover when using Optional data types – type casting.

When to use as? and when as

Let’s continue working with our imaginary UIKit app. Let’s assume you present a new modal view controller on screen (e.g by using presentViewController(_, animated:, completion:) ).

You define a custom view controller, which has an extra property called lastUpdated. Let’s suppose you wanted to change this property once the controller is presented. You can access the presented controller via the presentedViewController property on the main view controller:

presentedViewController is of Optinal type UIViewController? so you can easily unwarp the value and use it. But how about if you want to change the lastUpdated property, which you define in MyViewController and is not defined in UIViewController?

You can cast an Optional property by using as? like so:

as? tries to cast the value to the given type and if it doesn’t succeed returns a nil. That’s why the resulting type is always an optional value. You are forced to use as? also when the cast is not guaranteed to succeed – for example if you are trying to cast an AnyObject or Any value to a concrete class.

So, long story short, use as? if the cast could fail in any possible way.

As opposite to a possible failing cast when you use as? there’s also the cases where you are 101% sure that the cast will succeed and in those cases you can omit the ? and just cast by using as.

Let’s have a look as couple of examples when casting with as is useful.

Consider you are calculating the number of sheep on a farm. Through some weird math you get a fractional value, like in this example:

Now sheepCount is a Double and contains the value 35.5. Since you need an integer number and since casting from a Double to an Int is safe (e.g. will alwaus succeed by cutting off the floating part of the number) you can just cast the result to an Int like so:

In this case since the expression is casted to an Int type – also the sheepCount constant type will be Int (in contrast in the previous example sheepCount was of type Double)

Another case for as is when you are matching a pattern in a switch statement. In a switch you can always use as instead of a as? since the pattern is matched only when the cast succeeds. For example if you didn’t know what type sheepCount was – you can check that by passing it to a switch statement and try casting to different types in the different cases:

In each of the case statements the local, for that case, constant called sheep is of a different type – in the former case it’s of type Int and in the latter Double.

Where to go from here?

I hope that was a detailed introduction to how to use Optionals. Remember that is important not only for your code to work, but also for you to know how does it work :)

If you are interested to learn more about everything that has to do with Swift, consider reading my colleagues Colin Eberhardt and Matt Galloway’s book “Swift by Tutorials“.

By the way Swift by Tutorials is part of the iOS8 Feast where you can send a single tweet and have a chance to win some of the prizes in a total value of over $10,000. Read more here – iOS8 Feast.

Thanks for reading and I’ll see you next time.


RwDevCon – a raywenderlich.com conference in Washington, Feb 2015

After a truly long consideration and secret planning, scheming and speculation, dreaming and cold feet, heated discussions and planning – it has come to this: our very own conference!

The ray wenderlich tutorial team will hold a 2 day conference in Washington early next year, namely the February the 6th and the 7th.

You can find out more about the event and the location at the conf web site: www.rwdevcon.com and ask any questions or congratulate the team on the conf twitter account: @rwdevcon

However I just want to make a quick point here why I do believe this conference is very special.

The content of this conference is prepared by a team of developers and authors who work towards a common goal. That goal being to deliver an amazing end to end experience for the conference attendees.

The RwDevCon is not just a gathering of random presentations on interesting topics – it’s an experience designed to transfer to you the best and most knowledge in just two short days. We certainly have never produced an event like that – but hey the speakers at RwDevCon have developed a plethora of books, and we know about Apple technology and know how to deliver under pressure (talk about beta 6 and 7, brrr)

So, I believe that RwDevCon is going to be a unique event and no matter of what kind of technical level are you – you are going to have an awesome time if you come and join us in Washington next February.

Last but not least – this is a non-profit event; all proceeds are going to go towards making the conference the best you’ve seen. So, go ahead and book your ticket, because seats are not gonna be available much longer! NB: Currently there’s an Early Bird discount!

P.S. I’m incredibly happy to announce that I am one of the speakers to RwDevCon. Looking forward to meet you there!


This year I am to speak again at the Pragma Mark conference in Milano, Italy.I had great time last year and when they asked me to do a half a day workshop this year I agreed in a whim. I been hard at work this whole summer and have written tons of Swift and Sprite […]

My speaking schedule for 2014

I’m gonna be speaking at few conferences in 2014, so if you want to meet up – here’s where I’m gonna be.

Depending on how often you gather UDIDs from adhoc testers you might be unpleasantly surprised with iOS7. How gathering UDIDs worked up to iOS7 was by running a simple free app on the user’s phone which would then send you via email all the details like device model, UDID, version of iOS etc. However with […]

Even the best things break, and we’re just talking about CocoaPods here – a repo that thousands of people have write access to, rofl All in all the next time you go in the terminal and decide to update the managed libraries in your xcode project you will probably see something like this: M uriparser/0.7.7/uriparser.podspec […]