WatchKit Tutorial: How To Build Apple Watch App To Obtain Current Location

0
Shares
WatchKit Tutorial: How To Build Apple Watch App To Obtain Current Location
5 (100%) 1 vote

build apple watch app

Apple Watchkit was first released on 18th November, 2014 along with the Xcode 6.2 beta. For now, there are three types of Apple watch experience you can build: Watchkit apps, actionable notifications, and Glances.

Today, companies are hurrying to build Apple watch app to get ahead of the pack and send signal to market as well as customers that the company is an innovator.

Companies like MapMyFitness, Runtastic, and Nike have already arrived on the platform, but have not extended Apple watch support to more than 25% of their portfolios.

However, there are still many popular apps and games developed their Watch app to increase reliability for their users. And today, in this Watchkit tutorial, we’ll learn how to build Apple watch app and obtain current location of device.

Let’s Get Started

Before creating this demo, You must be ready with the system having iOS 10.0 SDK and Xcode 8.0.

WatchOS 2.0 is the minimum iOS version supported by this demo.

Most used Watch app methods:

awakeWithContext: When initializing the page, awakeWithContext method will be called. This is the first method to be called, and no UI is displayed yet.awakeWithContext will be called on ALL PAGES as soon as the watchOS app launches.

willActivate:  This method is called when watch view controller is about to be visible to user,
You should update label values, actions and anything else related to view elements.

here.willActivate will be called on ALL PAGES as soon as the watchOS app launches but this method will be called again as soon as you view the controller.

Now, Open your Xcode and click on “Create New Xcode Project”.

Select “Single View Application” and click on next.

screen-shot-2017-03-30-at-3-40-06-pm

Give you product Name and select language Swift in below screen press next button.

screen-shot-2017-03-31-at-12-46-42-pm

Now you base Project is ready Next step is click on File-> New>Target as shown in below screen.

screen-shot-2017-03-30-at-3-44-29-pm

This will open template choose screen where you need to select WatchOS -> WatchKit App->Next

screen-shot-2017-03-30-at-3-46-17-pm

Next, it will open one popup and ask you to activate the watch scheme. Select Activate option.

screen-shot-2017-03-30-at-3-49-37-pm

you have successfully created Watch kit extension this will create group of file in your
File inspector as below Image.

screen-shot-2017-03-31-at-2-52-30-pm

Here, InterfaceController.swift file is similar to ViewController file in ios application and ExtentionDelegate.swift file is similar to AppDelegate.swift in ios.

Now click on Interface.Storyboard from File Inspector it will open Storyboard like below screen.

screen-shot-2017-03-31-at-11-08-21-am

Now drag a map from object library to your watch storyboard, and add one button give name “Get Current location” and two other Label one for latitude and other for longitude as show in below screenshot.

screen-shot-2017-03-31-at-11-18-02-am

Now open Assistance editor and select map then click ctrl key and drag into InterfaceController file make an Outlet of map.

Similarly for both label and action for Button.

Here, the design work is finished in Storyboard.

Add Following keys in to you Info.plist file of you iphone application and as well as under CurrentLocation Extension info.plist file :

Privacy – Location When In Use Usage Description : I need location

Privacy – Location Always Usage Description : I need location

Now run the app. This will show your design on watch simulator but it won’t show location pin while click on button.

simulator-screen-shot-31-mar-2017-11-35-24-am

Now, next step to get user current location.

Add WatchConnector.swift file in your project and select watchDemo as well as CurrentLocation Extension as show in following screenshot (link of WatchConnecter file).

screen-shot-2017-03-31-at-11-40-02-am

Now you need to add coreLocation framework in you project.

Select WatchDemo from file inspector->Targets->BuildPhase->Link Binary With Libraries->clikc on (+) add CoreLocation.framework

Now got to your AppDelegate.swift file import following framework.

import CoreLocation
import MapKit

Then create variable for location like this:

let locationManager:CLLocationManager = CLLocationManager()
var currentLocation = CLLocation()

Add following code in your AppDelegate method.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
WatchConnector.shared.activateSession()

self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestLocation()
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
return true
}

Inherit CLLocationManagerDelegate in AppDelegate.swift file and add it’s delegate method like below.

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if locations.count == 0
{
return
}
self.currentLocation = locations.first!
let message = ["lat":self.currentLocation.coordinate.latitude,"long":self.currentLocation.coordinate.longitude]
WatchConnector.shared.sendMessage(message, withIdentifier: "sendCurrentLocation") { (error) in
print("error in send message to watch\(error.localizedDescription)")
}

}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Fail to load location")
print(error.localizedDescription)
}

Now go to your InterfaceController.swift file import coreLocation framework.

import CoreLocation

create variable like below.

var currentLocation = CLLocation()
var lat:Double = 0.0
var long:Double = 0.0

Add following code in your override func willActivate() method.

override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
WatchConnector.shared.listenToMessageBlock({ (message) in

self.lat = message["lat"] as! Double
self.long = message["long"] as! Double
print(self.lat)
print(self.long)

self.currentLocation = CLLocation(latitude: self.lat as! CLLocationDegrees, longitude: self.long as! CLLocationDegrees)

let mylocation : CLLocationCoordinate2D = CLLocationCoordinate2DMake(self.currentLocation.coordinate.latitude, self.currentLocation.coordinate.longitude)
let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
let region = MKCoordinateRegion(center: mylocation, span: span)
self.mapView.setRegion(region)
self.mapView.addAnnotation(mylocation, with: .red)
}, withIdentifier: "sendCurrentLocation")
}

Now, next step is to get latitude, longitude when click on get current location button.

@IBAction func btnGetCurrentLocationClicked() {
self.lblLatitude.setText("\(self.lat)")
self.lbllongitude.setText("\(self.long)")
}

Now run the app in watch it will run your iPhone app in iPhone simulator as well
After run app on watch open WatchDemo on iPhone Simulator and see there is pin shown on your  watch app.

simulator-screen-shot-31-mar-2017-12-30-24-pm

And done!

This Watchkit tutorial has covered the basics of integrating Maps into Watch app and use it to get the current user location. But, the Watchkit isn’t limited to this, you can also send actionable notifications or add Glances by developing a Watch app for your iPhone application.

Now, if you’re not aware about how to build Apple watch app, simply get in touch with a well-established wearable app development company that has experience of creating Apple watch apps to get your own Apple Watch app developed.

This page was last edited on July 24th, 2018, at 8:05.
 
0
Shares
 

Have an App Idea?

Get your free consultation now