02 – A basic Swift IOS app

Situm SDK can be used to build Wayfinding and Tracking applications, and dozens of use cases within those realms. However, there is a common pattern or skeleton that most Situm based applications will follow. In this Section, we provide an Swift iOS step-by-step guide to build your first Situm app based on this pattern.

Creating the project #

In Xcode go to “File” ->” New” -> “Project”.

Choose the App Template and “Continue”.

Configure your app name, team and identifier.

In this example will be selecting Storyboard as Interface and Swift as Language.

Select “Next” and create your app.

Import Situm SDK in your project dependencies #

First of all, you must configure Situm SDK in your iOS project. There are two ways to integrate SitumSDK in your project.

Create a Podfile in the root folder of your project and add a dependency with SitumSDK like this:

target '<your_target_name>' do
  use_frameworks!
  source 'https://github.com/CocoaPods/Specs.git'
  platform :ios, '11.0'
  pod 'SitumSDK', 'X.Y.Z'
end

Change the version number “X.Y.Z” with the latest available version of the SitumSDK (which you can find here).

After creating this file, open a console, go to your project’s folder and run pod install. This will download & link Situm SDK to your project, and create a file named project.xcworkspace: make sure you always use/open this one (not the project.xcodeproj file).

*If you need more information about Cocoapods, you can read it here.

Manual installation #

If you prefer to install Situm SDK manually, you will need to:

  • Link the following system libraries.
    • CoreLocation
    • CoreMotion
    • libc++.tbd
    • libz.tbd
  • Apply the -ObjC flag. In “Configuration”, under “Linking/Other Linker Flags”, add the flag “-ObjC”.
  • Disable Bitcode. Go to the “Build Settings” tab, search for the option “Enable Bitcode” and select “NO” as the value for that setting.

Then:

  • Download a version of SitumSDK from our repository (preferably, the latest stable version as per our changelog).
  • Drag the file SitumSDK.framework to your project (normally this should be included in a SitumSDK folder, inside your “Vendor” folder).
    • Make sure to check the option “Copy items if needed”. In recent versions of Xcode this automatically links your app with the framework (you can check this on the “Build phase” tab, “Link Binary with Libraries” section). Otherwise, add a link to the framework.

A word on Protobuf #

If your app (or any library you use) uses Protobuf, we strongly recommend you that you use Cocoapods (as explained in the previous section).

If you want to go ahead anyway, then you should use a version of our SDK that doesn’t use Protobuf included (available from version 2.31.3 or higher) and provide that dependency separately. You’ll recognize these versions in our repository because they are named such as “SitumSDK.noprotobuf.sdk”.

Run your first app! #

Grant app permissions #

An application running Situm will need certain permissions in order to work. First, in XCode you should go to the “Settings/Info” tab and create the following keys:

You will also need to add a description to each key, which will be shown to the user at the time the app request each specific permission. For example, to ask for LocationWhenInUse usage you should add the key “NSLocationWhenInUseUsageDescription” with the description “Location is required to find out where you are”. To ask for NSMotionUsageDescription you should add the key “NSMotionUsageDescription” with the recommended description “We use your phone sensors (giroscope, accelerometer and altimeter) to improve location quality”.

You can easily add these permisions by open your Info.plist file as “Source code” (you can choose this option via mouse left click) and copying this code snippet inside the property list dictionary:

<key>NSLocationWhenInUseUsageDescription</key>
<string>Location is required to find out where you are</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Location is required to find out where you are</string>
<key>NSMotionUsageDescription</key>
<string>We use your phone sensors (giroscope, accelerometer and altimeter) to improve location quality</string>
Example on how to configure the permissions and their keys.

Configure your AppBoundDomains #

You will also need to add the underlying web application’s domain inside the entry WKAppBoundDomains, also on Info.plist as follows:

<key>WKAppBoundDomains</key>
<array>
  <string>map-viewer.situm.com</string>
</array>

If you have other webviews in your app this might affect them, you can learn more about this here.

Location Authorization #

We provide some code that you can add to your project to handle the request of authorization to use location services. If you need more information you can check Apple documentation.

The authorizationHandler class make use of a delegate to notify when the authorization has been granted.

import Foundation
import CoreLocation

// Step 3 - Request Location Authorization
// We define a protocol to notify changes in location authorization.
// In this example we just manage the authorizationWhenInUse as is the one we need to startPositioning
protocol LocationAuthDelegate {
   func permissionHandlerAuthorizedWhenInUse()
}

class AuthorizationHandler: NSObject, CLLocationManagerDelegate{
    
    // Step 3 - Request Location Authorization
    var coreLocationManager: CLLocationManager?
    var delegate:LocationAuthDelegate?
    
    init(delegate:LocationAuthDelegate) {
        self.delegate=delegate
    }
    
    // Step 3 - Request Location Authorization
    func requestLocationAuth(){
        if (coreLocationManager == nil){
            //locationManagerDidChangeAuthorization is called when a CLLocationManager is configured.
            //https://developer.apple.com/documentation/corelocation/requesting_authorization_to_use_location_services
            coreLocationManager = CLLocationManager()
            coreLocationManager?.delegate = self
        }
    }
    
    
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        switch manager.authorizationStatus {
        case .authorizedWhenInUse:  // Location services are available.
            delegate?.permissionHandlerAuthorizedWhenInUse()
            break
            
        case .restricted, .denied:  // Location services currently unavailable.
            //disableLocationFeatures()
            break
            
        case .notDetermined: // Authorization not determined yet, request whenInUseAuthorization.
            coreLocationManager?.requestWhenInUseAuthorization()
            break
            
        default:
            break
        }
    }
}

ViewController #

To create your first app we will use the ViewController of your single View to perform the following actions:

  1. Import SitumSDK
  2. Set Situm Credentials
  3. Request Location Authorization
  4. Start Positioning
  5. Load the MapView

Each one of these steps is highlighted in the code with comments referencing the step number.

import UIKit
//Step 1 - Importing Situm
import SitumSDK


class ViewController: UIViewController, SITLocationDelegate, LocationAuthDelegate {
    
    // Step 3 - Request Location Authorization
    var authorizationHandler: AuthorizationHandler?
    // Step 4 - Positioning
    var sitLocManager: SITLocationManager = SITLocationManager.sharedInstance()
    
    // Step 5 - Load MapView
    // 1. Add a View to a the ViewController View in your Storyboard where you want the mapView to be shown.
    // 2. Set its class to SITMapView in the "Identity Inspector"
    // 3. Create this outlet from the storyboard to interact with the view
    @IBOutlet weak var mapView: SITMapView!
    var buildingID = "BUILDING_ID"
    var situmApiKey = "SITUM_API_KEY"
    var situmEmail = "SITUM_EMAIL"

    override func viewDidLoad() {
        super.viewDidLoad()
        // Step 2 - Setting credentials, we recommend to do this on your applicationDidFinishLaunchingWithOptions of the AppDelegate
        SITServices.provideAPIKey(situmApiKey, forEmail: situmEmail)
        // Step 4 - Positioning
        // Establish remote configuration ...
        SITServices.setUseRemoteConfig(true)
        //Step 3  - Request Location Authorization,
        authorizationHandler = AuthorizationHandler(delegate: self)
        authorizationHandler?.requestLocationAuth()
        // Step 5 - Load MapView
        loadMapView()
    }
    
    
    // Step 3  - Request Location Authorization, implement delegate that will get notified when authorization is granted
    func permissionHandlerAuthorizedWhenInUse() {
        startPositioning()
    }
    
    // Step 4 - Positioning
    func startPositioning(){
        //Create the request to activate positioning
        let request: SITLocationRequest = SITLocationRequest()
        
        //Start positioning by requesting location updates
        sitLocManager.requestLocationUpdates(request)
    }
    
    // Delegate functions to receive location notifications
    func locationManager(_ locationManager: SITLocationInterface, didUpdate location: SITLocation) {
        print("*POSITION UPDATED*\nPosition was updated to:\n Latitude: \(location.position.coordinate().latitude)\n Longitude:  (location.position.coordinate().longitude).")
    }
    
    func locationManager(_ locationManager: SITLocationInterface, didFailWithError error: Error?) {
        print("*POSITION UPDATED*\nThere was an error with the request: \(error?.localizedDescription ?? "")")
    }
    
    func locationManager(_ locationManager: SITLocationInterface, didUpdate state: SITLocationState) {
        print("*POSITION UPDATED*\nState was updated to \(state.rawValue)")
    }
   
    // Step 5 - Load MapView
    func loadMapView(){
        let mapViewConfiguration = SITMapViewConfiguration(buildingIdentifier: buildingID, floorIdentifier: "")
        mapView.load(with: mapViewConfiguration) { controller, error in
            guard error==nil else{
                print("Error loading map \(String(describing: error))")
                return
            }
            print("Map loaded properly")
        }
    }
}

Remember to add your own SitumCredentials and Building Id.

Now your are ready, run your app and enjoy!

Code Explanation #

We are going to explain now the previous five steps in more detail.

1. Import the headers #

To import the Situm SDK headers you can do it as follows:

import SitumSDK

2. Set Situm Credentials #

Great! At this point, you have correctly configured your Swift project. You can start writting your application’s code!

All you need to do now is introducing your Situm credentials (you can obtain them here) in your AppDelegate.swift file. There are two ways of doing this.

Option 1: using your email address and APIKEY (recommended) #

Write the following sentence on the -application:didFinishLaunchingWithOptions: method of your AppDelegate.swift file.

SITServices.provideAPIKey("SET YOUR APIKEY HERE", forEmail: "SET YOUR EMAIL HERE")

Please note! In the example we set the credentials in the ViewController but we recommend to do it in the AppDelegate.

3. Request Location Authorization #

In the example code the AuthorizationHandler class requests Authorization for using location services and comunicates to its delegate when the authorizedWhenInUse has been granted. To ge more information you can check Apple documentation.

4. Positioning #

Configure the positioning parameters #

Next, you will need to configure the positioning parameters. You may do this by building a LocationRequest object, as shown in the following example.

//You may insert this code in the ViewController where you want to start location updates

 let request: SITLocationRequest = SITLocationRequest()

The previous code will configure a SITLocationRequest with the default parameters. You may also set each parameter individually. To do this, you have two options:

  1. (Recommended) By using the Remote Configuration feature, that allows you to change the LocationRequest over-the-air using Situm Dashboard.
  2. (Not recommended) By manually setting the parameters in the LocationRequest builder.

Start Positioning #

To receive location updates you need to:

  1. Define the class that will implement the SITLocationDelegate protocol.
  2. Implement in that class the three mehtods where you will receive location updates:
    1. locationManager(locationManager:didUpdate location:): It will receive every new location produced. 
    2. locationManager(locationManager:didFailWithError error): It will receive every error produced in the SDK.
    3. locationManager(locationManager:didUpdate state): It will receive every status change produced in the SDK.
  3. Set that class as the delegate of SITLocationManager.
  4. Start the positioning by calling the SITLocationManager with the SITLocationRequest, which will contain the positioning configuration parameters (see previous Section).

Stop Positioning #

At any point you may choose to stop the positioning system. You may do so by calling the method removeUpdates method.

...

sitLocManager.removeUpdates()

5. Load the MapView #

  • Go to the Storyboard and add a View to the View of the ViewController where you want to show the map.
  • Set its class to SITMapView in the “Identity Inspector”
  • Create a outlet of your SITMapView from the storyboard to the ViewController class.
  • In the code of your ViewController:
    • Create a SITMapViewConfiguration with the buildingId of the building you want to show in the mapView (Optionally you can define a floorId to be shown in the first load)
    • Call the load method in your SITMapView with the previous configuration to load the View on the screen.

Next steps: take a look at all the code samples #

We have compiled a list of code samples which will teach you how to interact with Situm SDK to retrieve locations, handle cartography, compute routes and more.

Subscribe to our newsletter

BASIC INFORMATION ON DATA PROTECTION

Data controller: SITUM TECHNOLOGIES, S.L.
Contact: Data controller: situm@situm.es
Responsible for protection: dpo@situm.es
Purpose and legal basis: To manage the sending of SITUM newsletters only with consent.
Legitimation: Express consent of the interested party.
Recipients: The data will not be passed on to third parties with the exception of legal obligations.
Retention period: As long as the interested party remains subscribed to the newsletter (a link to unsubscribe will be available in each newsletter sent by Situm).
Rights: The interested party may at any time revoke their consent, as well as exercise their rights of opposition, access, conservation, rectification, limitation, deletion of data and not be subject to a decision based only on automated data processing, by writing to SITUM at the addresses indicated.
Additional Information: You can consult additional and detailed information on Data Protection in our privacy policy.

Please, download your copy here

Thank you for downloading our whitepaper. Please do not hesitate to contact us if you would like to know more about how our solutions can help your business. Download whitepaper


Close window