How do I display a value in a label (the value keeps changing/updating)

How do I display a value in a label in my Xcode app (the value keeps changing/updating)? So in my code, there is a pinned location and a user location, and I made some code to make a variable that tells the distance between the two points that continuously updates. I want to display this variable in a label so I can see how it updates. Here is my code:

                let value = userLocation.distance(from: pointLocation)

You have defined the label as

    @IBOutlet private weak var myLabel   : UILabel!  

Then, when needed:

myLabel.text = String(value)

it didn't work, it gave errors

That's not a useable answer. Please

  • show the complete code
  • Show where exactly you get the error
  • And what the error exactly is.

@claude31

I feel like the problem is not knowing where I should insert your code, so here is my entire code, and you determine which line I should put your code at (this is in the viewController btw):

import MapKit

import UIKit

import CoreLocation

import UserNotifications

class ViewController: UIViewController, CLLocationManagerDelegate {

    @IBOutlet var mapView: MKMapView!

    let manager = CLLocationManager()

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view.

    }

    override func viewDidAppear(_ animated: Bool) {

        super.viewDidAppear(animated)

        manager.desiredAccuracy = kCLLocationAccuracyBest

        manager.delegate = self

        manager.requestWhenInUseAuthorization()

        manager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        if let location = locations.first{

            manager.stopUpdatingLocation()

            render(location)

        }

        func render(_ location: CLLocation){

            let coordinate = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)

            let span = MKCoordinateSpan (latitudeDelta: 0.1, longitudeDelta: 0.1)

            let region = MKCoordinateRegion(center: coordinate, span: span)

            mapView.setRegion(region, animated: true)

            mapView.showsUserLocation = true


            let pin = MKPointAnnotation()

            pin.coordinate = coordinate

            pin.title = "your home"

            pin.subtitle = "Location"

            mapView.addAnnotation(pin)
            func userDistance(from point: MKPointAnnotation) -> Double? {

                guard let userLocation = mapView.userLocation.location else {

                    return nil // User location unknown!

                }

                let pointLocation = CLLocation(

                    latitude:  point.coordinate.latitude,

                    longitude: point.coordinate.longitude

                )

                //hello

                

                var value = userLocation.distance(from: pointLocation)

                return value
            }
        }
    }

    @IBAction func Button(_ sender: UIButton) {

        UIApplication.shared.open(URL(string: "https://www.gps-coordinates.net")! as URL, options: [:], completionHandler: nil)

    }
}






I do not see where you defined the label to write the coordinates. So you should create a Label in the view (in IB) and connect it to its IBOutlet (I call it positionLabel)

There is another big problem : userDistance() func is never called. So, I had to guess you want to call it on pin. I refactored your code a little.

Finally, func names should start with lowercase and have more explicit names.

  • First, disconnect the button from the IBAction
  • change the name
  • Reconnect

Replace

@IBAction func Button(_ sender: UIButton) {

with (for instance)

@IBAction func buttonTapped(_ sender: UIButton) {

Here is the modified code. If problem, please tell exactly where

1. import MapKit
2. import UIKit
3. import CoreLocation
4. import UserNotifications
5. 
6. class ViewController: UIViewController, CLLocationManagerDelegate {
7. 
8.     @IBOutlet var mapView: MKMapView!
9.     @IBOutlet private weak var positionLabel   : UILabel!  // <<< add this and connect to the label in IB
10. 
11.     let manager = CLLocationManager()
12. 
13.     override func viewDidLoad() {
14. 
15.         super.viewDidLoad()
16. 
17.         // Do any additional setup after loading the view.
18. 
19.     }
20. 
21.     override func viewDidAppear(_ animated: Bool) {
22. 
23.         super.viewDidAppear(animated)
24. 
25.         manager.desiredAccuracy = kCLLocationAccuracyBest // This should better be done in viewDidLoad
26.         manager.delegate = self // This should better be done in viewDidLoad
27.         manager.requestWhenInUseAuthorization()
28.         manager.startUpdatingLocation()
29.     }
30. 
31.     func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
32. 
33.         if let location = locations.first{
34.             manager.stopUpdatingLocation()
35.             render(location)
36.         }
37. 
38.    func userDistance(from point: MKPointAnnotation) -> Double? {  // >>> I took it outside for better readability
39. 
40.          guard let userLocation = mapView.userLocation.location else {
41.                     return nil // User location unknown!
42.           }
43. 
44.          let pointLocation = CLLocation(
45.                     latitude:  point.coordinate.latitude,
46.                     longitude: point.coordinate.longitude
47.                 )
48. 
49.           let value = userLocation.distance(from: pointLocation)  // replace var by let, as never changed
50.           return value
51.        }
52. 
53. 
54.   func render(_ location: CLLocation){
55. 
56.             let coordinate = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
57.             let span = MKCoordinateSpan (latitudeDelta: 0.1, longitudeDelta: 0.1)
58.             let region = MKCoordinateRegion(center: coordinate, span: span)
59.             mapView.setRegion(region, animated: true)
60. 
61.             mapView.showsUserLocation = true
62. 
63.             let pin = MKPointAnnotation()
64. 
65.             pin.coordinate = coordinate
66.             pin.title = "your home"
67.             pin.subtitle = "Location"
68. 
69.             mapView.addAnnotation(pin)
70. 
71.             if let distance = userDistance(from: pin) {     // >>> I call it here
72.                   positionLabel.text = String(distance)
73. 
74.            }
75.         }
76.     }
77. 
78.     @IBAction func buttonTapped(_ sender: UIButton) {
79. 
80.         UIApplication.shared.open(URL(string: "https://www.gps-coordinates.net")! as URL, options: [:], completionHandler: nil)
81. 
82.     }
83. }

the label isn't showing the value

It doesn't show when ? Maybe render() func is never called. To check, add line 55 : print("Render") and line 73: print("distance", distance)

error message in AppDelegate says,"Thread 1: "-[Project.ViewController buttonTapped:]: unrecognized selector sent to instance 0x133e08da0""

You probably did not do what I told you:

  • First, disconnect the button from the IBAction
  • change the name
  • Reconnect

So, now, in IB, select the button and open the connections inspector. Uncheck the link to IBAction. It should look like this: click on the small x to disconnect.

Now, control drag from the small circle on the left of IBAction buttonTapped to the button to reconnect. And do an option clean Build folder.

Tell what you get after those changes.

@Claude31, the button in this project has nothing to do with the label I made displaying the live distance from a pinned spot. And in your code, the label doesn't show anything, so please tell me how to fix this

If you do not explain more clearly the set up, it is nearly impossible to help.

the button in this project has nothing to do with the label 

But you say you have an error message when button is tapped. Which button is it ?

error message in AppDelegate says,"Thread 1: "-[Project.ViewController buttonTapped:]: unrecognized selector sent to instance 0x133e08da0""

When does the location update ? When user moves ? On simulator or on device ?

How much distance does it move ? If less than a few meters, that may not be enough to detect.

Could you instrument the code with some print statements (lines 32, 70, 73) And tell exactly what you get.

1. import MapKit
2. import UIKit
3. import CoreLocation
4. import UserNotifications
5. 
6. class ViewController: UIViewController, CLLocationManagerDelegate {
7. 
8.     @IBOutlet var mapView: MKMapView!
9.     @IBOutlet private weak var positionLabel   : UILabel!  // <<< add this and connect to the label in IB
10. 
11.     let manager = CLLocationManager()
12. 
13.     override func viewDidLoad() {
14. 
15.         super.viewDidLoad()
16. 
17.         // Do any additional setup after loading the view.
18. 
19.     }
20. 
21.     override func viewDidAppear(_ animated: Bool) {
22. 
23.         super.viewDidAppear(animated)
24. 
25.         manager.desiredAccuracy = kCLLocationAccuracyBest // This should better be done in viewDidLoad
26.         manager.delegate = self // This should better be done in viewDidLoad
27.         manager.requestWhenInUseAuthorization()
28.         manager.startUpdatingLocation()
29.     }
30. 
31.     func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
32.         print(#function, "didUpdateLocations")     // To see if this is called
33.         if let location = locations.first{
34.             manager.stopUpdatingLocation()
35.             render(location)
36.         }
37. 
38.    func userDistance(from point: MKPointAnnotation) -> Double? {  // >>> I took it outside for better readability
39. 
40.          guard let userLocation = mapView.userLocation.location else {
41.                     return nil // User location unknown!
42.           }
43. 
44.          let pointLocation = CLLocation(
45.                     latitude:  point.coordinate.latitude,
46.                     longitude: point.coordinate.longitude
47.                 )
48. 
49.           let value = userLocation.distance(from: pointLocation)  // replace var by let, as never changed
50.           return value
51.        }
52. 
53. 
54.   func render(_ location: CLLocation){
55. 
56.             let coordinate = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
57.             let span = MKCoordinateSpan (latitudeDelta: 0.1, longitudeDelta: 0.1)
58.             let region = MKCoordinateRegion(center: coordinate, span: span)
59.             mapView.setRegion(region, animated: true)
60. 
61.             mapView.showsUserLocation = true
62. 
63.             let pin = MKPointAnnotation()
64. 
65.             pin.coordinate = coordinate
66.             pin.title = "your home"
67.             pin.subtitle = "Location"
68. 
69.             mapView.addAnnotation(pin)
70.             print(#function, "userDistance(from: pin) ", userDistance(from: pin) )
71.             if let distance = userDistance(from: pin) {     // >>> I call it here
72.                   positionLabel.text = String(distance)
73.                   print(#function, "distance", String(distance))
74.            }
75.         }
76.     }
How do I display a value in a label (the value keeps changing/updating)
 
 
Q