Home>

I want to get latitude.text from realtimedatabase by pressing UIButton, but an unknown nil is returned and an error occurs (Unexpectedly found nil while unwrapping an Optional value)
See this page I didn't know how to solve it. Please give me advice.

import UIKit
import MapKit
import CoreLocation
import Firebase
class FirstViewController: UIViewController, CLLocationManagerDelegate {
    @IBOutlet weak var mapView: MKMapView!
    @IBOutlet weak var latitude: UILabel!
    @IBOutlet weak var longitude: UILabel!
    let user = Auth.auth (). currentUser? .uid
    let locationManager = CLLocationManager ()
    var ref: DatabaseReference!
    var otherUserLatitude: String? = nil
    var otherUserLongitude: String? = nil
    override func viewDidLoad () {
        super.viewDidLoad ()
        ref = Database.database (). reference ()
        locationManager.delegate = self as! CLLocationManagerDelegate
    }
    // Can save
    @IBAction func userLocation (_ sender: Any)
    {
        let userCoordinate = ["userLatitude": latitude.text]
        ref.child ("users"). setValue (["userCoordinate": userCoordinate])
        print ("Location information saved")
    }
    @IBAction func othersLocation (_ sender: Any)
    {
        // Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value error
        ref.child ("userLatitude"). child (user!). observeSingleEvent (of: .value, with: {(snapshot) in
        let value = snapshot.value as? NSDictionary
        let otherUserLatitude = value? ["userLatitude"] as? String
        print ("User latitude:", otherUserLatitude)
        })
    }
    func locationManager (_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        switch status {
        case .notDetermined:
            locationManager.requestWhenInUseAuthorization ()
        case .authorizedWhenInUse:
            locationManager.startUpdatingLocation ()
        default:
            break
        }
    }
    func locationManager (_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let coordinate = locations.last? .coordinate {
            // Zoom in on your current location
            let span = MKCoordinateSpan (latitudeDelta: 0.01, longitudeDelta: 0.01)
            let region = MKCoordinateRegion (center: coordinate, span: span)
            mapView.region = region
        }
        guard let newLocation = locations.last else {
                return
        }
        self.latitude.text = "" .appendingFormat ("%. 4f", newLocation.coordinate.latitude)
        self.longitude.text = "" .appendingFormat ("%. 4f", newLocation.coordinate.longitude)
        let location = locations.first
        let latitude = location? .coordinate.latitude
        let longitude = location? .coordinate.longitude
        print ("Latitude: \ (latitude!) \ nLongitude: \ (longitude!)")
    }

}


Information in realtimedatabase

  • Answer # 1

    Can you get this?

    @IBAction func othersLocation (_ sender: Any)
    {
    // Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value error
    ref.child ("users"). child ("userCoordinate"). observeSingleEvent (of: .value, with: {(snapshot) in
    let value = snapshot.value as? NSDictionary
    let otherUserLatitude = value? ["userLatitude"] as? String
    print ("User latitude:", otherUserLatitude)
    })
    }

    It should be setValue

    let userCoordinate = ["userLatitude": latitude.text]
    ref.child ("users"). child (user!). setValue (["userCoordinate": userCoordinate])


    To get it

    ref.child ("users"). child (user!). child ("userCoordinate") ...