iOS Swift Tutorial: Location and Maps

Just another WordPress site

iOS Swift Tutorial: Location and Maps

hi and welcome to another very exciting tutorial today we’re going to explore the possibilities of the map view and we’re going to discuss all of the important steps that lead to a to a map view implementation which includes adding the reason for example why you want to use the user’s location which we have to provide in the info.plist file so here is the little demo application that we are going to build which is very simple we have a map view here at the top and two labels one with the my location text and beneath that we’ve got the address of our pin here so we are also going to discuss how to place a pin on the map of course we can also update our location but this doesn’t make a lot of sense within the simulator where we can’t really change our location easily so let’s go ahead and dive right into Xcode and create a new single view application which is going to be called my location and hitting next and we’ll just save it on the desktop and I’m going to resize my Xcode window here and the first snap that we need to do actually is embedding or link our project with the map kit framework so what we are going to do is we look for the linked frameworks and libraries click the plus icon here and then type in map kit in the search field at the top of this at the top of the Xcode window and we add now the map kit framework so that’s the first step the separate the second step is going to be that we want to create our really simple user interface clicking on the main storyboard file and here it is our empty view controller and what we want to do is actually really simple we search for the map kit view would just drag and drop it to our viewcontroller and we will resize it something like that so that it feels quite a big amount of the screen and then we will also add some labels so just searching for a label here and positioning it here beneath the map kit view so this is going to be my location column and also another another label where we will place the address which we will get from from our map kit or the the real geolocation of the user position that a little here a little more to the left and what we also want to do is adding a button which will be responsible for updating the map user just type in up date and I will set some constraints in order for our view to be because it’s a position correctly on different devices so we will click on the map view press control on the keyboard and simply drag to the view here in our document outline so now we are going to select the leading space the trailing space and the top space to layout guide and hit enter on the keyboard and then we will simply press control again and click drag within the MK map view and select the height so that we have a constant height on every device and then we will give our location a little higher font size something like that make this a little bigger and also give the my location some constraints which will be a vertical spacing to the map view and a leading space which actually should do it in that case we will update the constraints in a second because as you can see there are some blue lines but they’re also red and and yellow or orange lines but we’re going to correct that in a second and also we are going to set the constraints for our real address so first of all a vertical spacing and we will increase the size a little and also make a leading space to contain a margin and a trailing space and let’s do the same thing for for our Update button which will get a constraint for the bottom space to bottom layout guide and also we are going to Center it horizontally in the container and now as you as you have

already seen we have some red lines and we can all yellow lines and we can simply have a look at the viewcontroller scene and click on this yellow icon here and as you can see here we have some expected locations which we will need to update so let me zoom out a little and go into the size inspector here on the right and as you can see we have and expected width of 131 pixels and actual width of 134 so let’s simply correct that one three one and also height is expected 28 so let’s type in 28 and that’s it and for the New York label we will actually need a Y position of 4 5 9 so Y 4 5 9 and that’s it now we have our user set up user interface setup and we can now make some connections so let’s bring up the assistant editor and make an outlet for our map view so let’s just call it map view and also let’s make an outlet for our address label or let’s say location info and what we also need is an action for our button which is going to be called update location and make sure that you select as a connection and action and not an outlet and let’s click connect and that’s it and as you can see here in the assistant editor already we have an arrow which tells us that we use an undeclared type which is MK map view so what we need to do is import mapkit to our viewcontroller.swift file and build that and as you can see build succeeded and that was actually the first steps of creating an app which uses the location services of the iPhone and I also want to give you a little a little tip here for working with locations there are some great some great predefined classes which you can use from from github and we have a location manager here which is really quite handy and it’s already written in Swift and so just go ahead and download that we’re going to use it in a moment and this will really make our work a little easier than using all the Apple default classes so just go ahead and download the zip file you’ll find the URL for this for this class for this github project in the video description so I have downloaded it and let me just open it and what we want to do now is simply using the location manager Swift file and drag it to our project and make sure that you select destination copy items if needed and click finish and now I can use this location manager class and since the introduction of iOS 8 we have to specify the reasons why we want to use the users location and we have two two modes that we can select which I have copied to make no mistake you and there are two two reasons that we have to describe one is the when in usage when in use usage description so this would tell our application that we you want only want to get the users location when the app really is used em in foreground and the always usage description describes that we want to use the location of the user even if the user doesn’t use the app at the moment so when we can make background refreshes of the location when using this description and for the simplicity of this tutorial I’m going to select the NS location all the ways usage description and simply copy that you can of course also use this description key depending on your application that you want to build so I have copied this this key here and what what I want to do is pasting it in the info.plist this is where we have to define the description and so I’m opening up my supporting files and opening up the info.plist and now I’m going to right click and add a new row and now I’m going to paste this key and now I can add a value which is of type string and this is the description and now I have to state why I want to use the user’s location always even if the app is in background so I’m going to say

to update the map you can of course um choose whatever description you like it should be very exact and short of course because many users do not read that but we have to provide it anyway so this is the first step and now we can actually move on to our view controller file and do some stuff with the user’s location so first of all what we want to do is defining a location manager where we will use the apple core location manager so this is going to be a property we will call it core location manager and it will we will initialize it right here with CL location manager and that’s it this is the first thing we need to do and we also want to use this location manager class which we’ve downloaded from from github later but we will also define the the property associated with this class later so what we also need is the CL location manager delegate so that’s also adopt that protocol see a location manager delegate and now we will set up all that stuff in the viewdidload method so first of all um we will remove that comment here and now we are going to tell our core location manager that it’s delegate is going to be self so this was the first step now the first time we are going to launch our app we wanted to ask the user for authorization for our to use the location so what we what we’re going to do is we will create a constant here which we called aw for ization code and we will then use the CL location manager and simply use its authorization status property and now we have the authorization code which we can use to make an if statement and we can now ask if the authorization code is equal to CL authorization status not determined so if the user has not yet decided if he wants to allow our app to use his or her location and then it is not determined so then we can actually ask for a specific specific authorization status which is either always allowed or only when in use so we will also ask within this if statement if the core location manager responds to the selector request always all theorization and if this is the case then we can and then we can actually request the the location service for our app but we could also include an hour statement here and also ask for Cora location manager responds to selector requests when in use authorization so we can do both things here and in our if within our cope lock here we need to do another if statement so we need to ask if there is this description so we say NS bundle main bundle object for info dictionary and now we have to use the Ana’s location always usage description key which we have to find in the info P list and of course and using the anis bundle main bundle object for info dictionary key we get into our info.plist file and can ask if this is not equal to nil so that means that we have provided a description for the always usage request and if this is available so if this description is available we can say core location manager request request always authorization and you can also see that here is also the request when in use authorization and depending on what you want to do you can then change this NS location always usage two when in use and then call the when in use method here using the core location manager property so this was the first part of this if statement and there’s also an else part where we will simply say that there was no description provided so no description provided is going to help you if you have not yet provided a

description it will also tell you this in your console so that you can then go ahead and make the adjustments to the info.plist so this is actually only going to happen this request always authorization when the user has not yet determined if he wants to allow our application to use his current location this code however should only be called once when the application starts for the first time because then the user has determined if he or she wants our application to to get his or her current location so if the authorization code is not equal to not determined so if we have another authorization code which should indicate that we are allowed to use the user’s location then we can actually do what our application is supposed to do which is of course getting the user’s location so we will simply call a method called get location here which we will implement now so this is going to be a new function as you can see it’s called ghat location we have no parameters here and what it does is actually pretty simple we can now use the location manager the custom location manager that we have downloaded from github so we will define a new property for that location manager so we say location manager which is going to be an of the type location manager and we will then initialize this location manager in viewdidload so we can simply say location manager equals capital L location manager dot shared instance and that’s actually all there is to getting this location manager up and running and since we now have this new property we can use it’s really convenient functionality and I’m going to call the location manager and simply call start updating location with completion Handler and this completion handler gives us all the information we need like latitude longitude status verbose method and message and an error message and you can of course use the this error object in order to print a lot of information to the user and make it really transparent what’s not working at the moment but for simplicity’s sake we will just skip that and simply call another function here that we’re going to implement which is going to be called display location this will get a parameter which is a location of type CL location which is this one and we will then use this this location in a second so let’s just call that display location method within our get location method so let’s say self display location and we have to use self because we are within a closure so we will now provide this display location method with the parameter it asks for which is the location so we will create a CL location object with a latitude and longitude and these two properties we actually get from the completion handler here so let’s simply provide provided with the latitude and the longitude and that’s it and now that we have our our parameter here provided with the necessary information and we can go ahead and use our map view to display this location so let me make some space here and we will call our map view and set its region so let’s call set region and as you can see it asked for an MK coordinate region so we will provided with one so MK coordinate region and this again once a center which is going to be a CL location coordinate to D so again CL location coordinate to D and we will use the make B make constructor here and we will now provide it with a longitude and latitude again and we will get that from our parameter location so location dot latitude dot coordinate dot latitude and again location Cornette dot longitude and now it asks as far as span so this is where what it actually which area which span of area it should display so here we will also use the MK coordinate coordinate span make and we’ll use a

delta of let’s just say 0.05 and again 0.05 and you can of course chooses if you want it to be animated or not I choose it to be ad that it should be animated which looks quite cool actually so this is to set the region of the map so that we can have the proper area displayed on the screen in order for us to set a red pin to our exact location we will again get a coordinate object which is going to be delivered the location pin coordinates and we will get them again by using see a location coordinate 2d and give that the two the two parameters we need which is again location dot Carnot dot latitude and location coordinate dot longitude and now that we have this these coordinates we can create a so-called point annotation so let’s say let a notation is going to be MK point annotation and we’ll simply initialize that that constant and now we’ll set the annotations coordinates to the location pin coordinates so this was the first step and now we can simply add the annotation to our map view using the add annotation functions of annotation and then all we need to do now is calling map view again and show our annotations which requires an array so you can imagine that you can provide this show annotations a method with a bunch of pins which you our familiar with from the the map app on every iPhone so if you search for sushi in your area you will find a bunch of pins on your map and this is the way it works and so we will only provide an array using records for our annotation that we have defined and then we can simply also tell this function that it should be animated so this is the first step and if we were to run this application now we wouldn’t see a lot of things because we need to we need to authorize first and as you can see only if the only if the user already has authorized our app to use its location we can call our ghat location we can call our gaap location function so to change that we have already adopted the the CL location manager delegate and there is a quite handy delegate method which is called a location manager um it is did update did determine oh did change authorization status and that’s that’s pretty cool so now we can actually ask if the status is not equal to CL authorization status not determined or status is unequal to see authorization status denied or status is not equal to seal authorization status restricted that means that if their status has changed and it is neither not determined nor denied nor restricted then we can get the location and so now we can give it a try and run our application for the first time but note that if you try to run an application that needs to that needs to use the users location if you want to simulate that using the IOA iPhone simulator what you need to do for example is clicking on the active schemes and then edit the scheme and then you find the scheme options here and you need to check allow location simulation and then you can also select default location like Hong Kong for example and click close and then once we run the application that should work actually quite nicely so let’s see and there we are at the moment we are somewhere within the ocean and now as you can see here is to update the map this is the description we provided in the info P list and our app asks allow my location to access your location even when you are not using the app reason to update the map ok and now we can click allow and as you can see now our location changed to Hong Kong and this

is because we have implemented that the change authorization status delegate method which directly called get location once it’s authorization status has changed so that was the first step now as you recall from the little demonstration at the beginning of this tutorial we also want the exact address of our location of this red pin so what we need to do is a reverse geocode the location that we have provided we got from from the from the GPS coordinates that our app possess is already in display location so to do that we can also again use the location manager this has some really convenient functions as you can see so we will use the display location function for that reason as well as well and call the location manager and a call reverse geocode location with coordinates and as you can see here you can also use and Google as a service here to reverse geocode the that we have provided here as parameter so we will simply use reverse geocode location with coordinates and this wants us to provide this function with some coordinates with which we already have here as our location parameter and then you can see here a completion handler on reverse geocoding completion Handler and there it is and when we print line this reverse geocode info you can see that we get quite a bunch of useful information so let me run our application again and when we have a look at the Consul down here you can see a lot of information and what we are going to use is simply the formatted address and as you can see you could use a lot of that stuff the country the administrative area and the latitude and longitude again the street number and the sub locality and you get the idea you have a lot of information here which you can process within your app so we what don’t want to print land that but what we want to do is and get the address and we will do that using the reverse geocode infill use the object for a key accessor and then we want the four method address and then cast that to a string and then we can use self dot location info which is the label that we have created in the interface builder earlier use its text property and provided with the address and once we build that build succeeded and then we can run our application again and as you can see there we are we have the street we have the city and to change our location and the simulator there’s that’s quite tricky so we have to deactivate a simulator press command Q and then we have to go to the scheme again select let’s say London and run the application again and then as you can see now we are here in London at the Piccadilly a duplicated Lee Circus and that’s it actually all we need to do now is provide our update button here with some functionality and as you can see here all we need to do is again call the get location function within the IB action that we have already that we’ve already created and as you can see once we click on update location we really do the update and this is really pretty simple so what you have to keep in mind is a link to the map kit framework and the one of the two description keys and of course the description to your info.plist and if you want you can use this location manager Jimmy Jose which is really great and really convenient I highly recommend using it and that’s it actually so these aren’t simple steps to get your users location have fun