- Creating an iOS app that pulls and displays GPS data in real-time.
---
### **Lab Workbook: Creating an iOS App to Access and Display GPS Data**
**Objective:**
By the end of this lab, students will have created an iOS app using Xcode that accesses and displays the iPhone's current GPS coordinates (latitude and longitude) on the screen in real-time.
This will introduce key concepts such as
the Apple CoreLocation library,
setting permissions,
creating basic user interface elements in Swift.
---
Prerequisites:
- **Xcode Installed** (latest version from the Mac App Store)
- **iOS Device** (or simulator, but real devices work best for GPS)
---
### **Section 1: Project Setup in Xcode**
Step 1: Create a New Xcode Project**
1. Open **Xcode**.
2. On the welcome screen, click **“Create a new Xcode project”**.
3. Select **“App”** under iOS.
4. Click **Next**.
#### **Step 2: Set the Project Details**
1. **Product Name**: Enter a name, e.g., "GPSApp".
2. **Team**: If you have an Apple Developer account, select it here. If not, you can use “None” for development on simulators.
3. **Organization Identifier**: A reverse domain name (e.g., com.yourname).
4. **Interface**: SwiftUI (we’re going with SwiftUI for simplicity).
5. **Language**: Swift
6. Click **Next**.
7. Choose a location to save the project and click **Create**.
Section 2: Requesting Location Permissions
iOS apps need explicit permission to access sensitive data like location.
Let's start by modifying the app to request GPS access.
Step 3: Modify the Info.plist
The `Info.plist` file stores essential app configuration details, including privacy settings.
1. In the Xcode Project Navigator (on the left), find and click on **Info.plist**.
2. Add the following **Privacy Key** by hovering over the last key and pressing the **+** button:
- **Key**: `NSLocationWhenInUseUsageDescription`
- **Value**: A description of why the app needs GPS, e.g., “This app needs access to your location to display your current GPS coordinates.”
This key makes sure that when the app asks the user for permission, iOS displays this message.
To access the iPhone's GPS, we need to use **CoreLocation**, the framework responsible for location services in iOS.
Step 4: Import CoreLocation and Update the SwiftUI View
1. Open **ContentView.swift**.
2. At the top of the file, add the import for CoreLocation:
```swift
import SwiftUI
import CoreLocation
```
Step 5: Create a Location Manager Class
The `CLLocationManager` is the key class that handles all GPS data.
We’ll create a LocationManager class to manage the user’s location and pass the coordinates to our SwiftUI view.
1. **Create a new Swift file**:
- Right-click on the **GPSApp** folder in the Project Navigator.
- Select **New File > Swift File**.
- Name the file **LocationManager.swift**.
2. Add the following code to `LocationManager.swift`:
```swift
import Foundation
import CoreLocation
**Explanation**:
- `CLLocationManager`: Handles GPS functionality.
- `requestWhenInUseAuthorization()`: Asks the user for permission to use GPS.
- `didUpdateLocations`: Updates the location in real-time and stores the latest GPS coordinates.
Step 6: Inject the LocationManager into SwiftUI
1. Go back to **ContentView.swift** and update it like this:
```swift
import SwiftUI
import CoreLocation
struct ContentView: View {
@StateObject var locationManager = LocationManager()
var body: some View {
VStack {
if let location = locationManager.location {
Text("Latitude: \(location.coordinate.latitude)")
Text("Longitude: \(location.coordinate.longitude)")
} else {
Text("Fetching location...")
}
}
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
```
**Explanation**:
- **@StateObject**: This creates an instance of the `LocationManager` that stays in memory.
- If location data exists, it displays the latitude and longitude, otherwise, it shows "Fetching location…".
---
Section 4: Running the App
Step 7: Run the App on Simulator or Device
1. Plug in your iOS device (or select an iOS simulator, but real GPS is only available on physical devices).
2. Select the device from the top bar next to the "Run" button.
3. Press **Command + R** or click the **Run** button to launch the app.
#### **Testing Location on a Simulator:**
- If you're using a simulator, it won't have real GPS. However, you can **simulate location data**:
1. In the Simulator, click **Features > Location**.
2. Choose a location (e.g., Apple’s headquarters).
Your app will now display those simulated coordinates!
---
### **Section 5: Enhancements (Bonus)**
If you and the students are feeling confident, here are some next steps to enhance the app:
#### **Bonus 1: Add a MapView**
Add a Map to visually show the user’s location:
1. Import **MapKit**:
```swift
import MapKit
```
2. Add this below the GPS coordinates in **ContentView.swift**:
```swift
Map(coordinateRegion: .constant(MKCoordinateRegion(
center: locationManager.location?.coordinate ?? CLLocationCoordinate2D(),
span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
)))
.frame(height: 300)
```
#### **Bonus 2: Display Address**
Use **reverse geocoding** to display the user’s current address:
1. In the `LocationManager.swift` file, add this method inside the class:
```swift
func fetchAddress(for location: CLLocation, completion: @escaping (String?) -> Void) {
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(location) { placemarks, error in
if let place = placemarks?.first {
let address = "\(place.name ?? ""), \(place.locality ?? ""), \(place.country ?? "")"
completion(address)
} else {
completion(nil)
}
}
}
```
2. Modify **ContentView.swift** to show the address once it’s fetched:
```swift
@State private var address: String? = nil
var body: some View {
VStack {
if let location = locationManager.location {
Text("Latitude: \(location.coordinate.latitude)")
Text("Longitude: \(location.coordinate.longitude)")
if let address = address {
Text("Address: \(address)")
} else {
Text("Fetching address...")
.onAppear {
locationManager.fetchAddress(for: location) { addr in
self.address = addr
}
}
}
} else {
Text("Fetching location...")
}
}
.padding()
}
```
---
### **Wrap-Up**
We have now built a basic GPS-powered iOS app
We can now access location data, and use the essentials of working with **CoreLocation** in Swift.
We are well our way to building Travelogue App.
Yay, look at that! You're almost there! 🎉 Now let’s get that GPS app running on your iPhone. We’ll walk through the steps for **side-loading** the app from Xcode to your physical device. Let’s do this! 💪😊
---
### **Steps to Run Your App on a Physical iPhone from Xcode**
#### **Step 1: Connect Your iPhone to Your Mac**
1. Plug your iPhone into your Mac using a USB cable.
2. Unlock your iPhone (if it’s locked), and if prompted, select **"Trust This Computer"** on your iPhone.
3. Enter your iPhone’s passcode if requested.
#### **Step 2: Set Your iPhone as the Deployment Target**
1. In **Xcode**, at the top, you should see a device selector near the "Run" button (the triangle play icon). Right now, it’s probably set to "iPhone 15 Pro (Simulator)" or a similar simulator name.
2. Click the device dropdown and select your **physical iPhone** from the list. If you don’t see your iPhone, try reconnecting it or make sure you’ve trusted your Mac from the iPhone.
#### **Step 3: Configure Code Signing**
Since you’re running the app on a physical device, Xcode needs to sign the app.
1. Go to the **"Signing & Capabilities"** tab of your project:
- In the Project Navigator (the panel on the left), click the project’s root folder (**GPSApp**).
- Click the **GPSApp** target under **TARGETS**.
- Switch to the **"Signing & Capabilities"** tab.
2. Make sure **"Automatically manage signing"** is checked.
3. Under **Team**, select your **Apple ID** or **Personal Team** (if you’re using a free developer account).
- If you don’t have an Apple Developer account linked, you’ll need to add it here. Go to **Xcode > Settings > Accounts**, and sign in with your Apple ID.
> **Free Developer Account Note**: If you're using a free Apple Developer account (instead of a paid one), you may face some limitations, such as apps expiring after 7 days. That’s totally fine for testing!
4. Xcode will take care of generating the necessary provisioning profile for you.
#### **Step 4: Run the App on Your iPhone**
1. With your iPhone selected and code signing set up, hit **Command + R** or click the **Run** button (the triangle) in the toolbar.
2. If this is your first time installing an app on your iPhone from Xcode, you might see a message on your phone: **"Untrusted Developer"**.
**Fix for Untrusted Developer**:
- Go to your iPhone's **Settings**.
- Navigate to **General > Device Management**.
- Under **Developer App**, you should see your Apple ID.
- Tap it and click **Trust [Your Apple ID]**.
#### **Step 5: Allow Location Access**
When the app launches on your iPhone, it will prompt you to allow location access. You must grant this permission for the app to fetch GPS data:
1. Choose **"Allow While Using the App"** when the permission popup appears.
---
### **Common Issues and Fixes:**
#### **Issue: "Failed to code sign" Error**
- Make sure you've selected your **Apple ID** in the **Team** section under **Signing & Capabilities**.
- If using a free Apple Developer account, make sure your iPhone is connected and you've trusted the developer.
#### **Issue: App Crashes Immediately**
- Make sure location permissions are granted.
- Double-check the **Info.plist** entry: Ensure the key `NSLocationWhenInUseUsageDescription` has a proper description for why the app needs GPS access.
---
That should be it! If everything goes well, your app should pop up on your iPhone, and you’ll see those GPS coordinates being fetched in real-time! 🌍📱✨
How exciting is that?! You’ve built your first GPS-enabled iOS app and got it running on your own iPhone—*so proud of you*! 🥳
Want to print your doc? This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (