Question about saving user current location into database












1















I am trying to save user current location to firebase that include time and address. Basically, my code is working, but just the first location address always shows "label", not address. Therefore, when I re-run the app, it always has a label data in my firebase realtime database. I don't know how to fix it. I attached my code and the picture of my database below.



func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if locations.count > 0 {
let location = locations[locations.count-1]
let maxAge:TimeInterval = 60;
let requiredAccuracy:CLLocationAccuracy = 80;
let locationIsValid:Bool = Date().timeIntervalSince(location.timestamp) < maxAge && location.horizontalAccuracy <= requiredAccuracy;
if locationIsValid
{
NSLog(",,, location : %@",location);
NSLog("valid locations.....");
}
}

let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: locations[0].coordinate.latitude, longitude: locations[0].coordinate.longitude), span: MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005))
self.mapView.setRegion(region, animated: true)

CLGeocoder().reverseGeocodeLocation(manager.location!) { (placemarks, error) in
if error != nil{
print("Error: " + (error?.localizedDescription)!)
return
}
let pm = placemarks! as [CLPlacemark]
if pm.count > 0 {
let pm = placemarks![0]

let subThoroughfare = pm.subThoroughfare ?? ""
let thoroughfare = pm.thoroughfare ?? ""
let locality = pm.locality ?? ""
let administrativeArea = pm.administrativeArea ?? ""
let postalCode = pm.postalCode ?? ""
let country = pm.country ?? ""
let address = (subThoroughfare)+" "+(thoroughfare)+" "+(locality)+","+(administrativeArea)+" "+(postalCode)+" "+(country)

self.myAddress.text = "(address)"
}
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd, HH:mm:ss"
formatter.timeZone = NSTimeZone.local
let timestampFormattedStr = formatter.string(from: (locationManager.location?.timestamp)!)
let timeZone = NSTimeZone(forSecondsFromGMT: NSTimeZone.local.secondsFromGMT())
let timeZoneName = timeZone.localizedName(.standard, locale: NSLocale.current)
let timestampWithTimeZone = "(timestampFormattedStr) (String(describing: timeZoneName))"
let values = ["Time": timestampWithTimeZone,"Address": myAddress.text as Any]

let ref = Database.database().reference()
ref.child("userLocations").childByAutoId().setValue(values)
}


And below is the picture of my database
enter image description here










share|improve this question























  • At first time while reverseGeocodeLocation was decoding, you saved address into Firebase.

    – Surjeet
    Nov 21 '18 at 18:32











  • Call Firebase line inside reverseGeocodeLocation block, when received address. You problem will be fixed. Let me know, If you need any other help.

    – Surjeet
    Nov 21 '18 at 18:33













  • @Surjeet How to do that? Sorry I am new in this field.

    – Adam
    Nov 21 '18 at 18:51
















1















I am trying to save user current location to firebase that include time and address. Basically, my code is working, but just the first location address always shows "label", not address. Therefore, when I re-run the app, it always has a label data in my firebase realtime database. I don't know how to fix it. I attached my code and the picture of my database below.



func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if locations.count > 0 {
let location = locations[locations.count-1]
let maxAge:TimeInterval = 60;
let requiredAccuracy:CLLocationAccuracy = 80;
let locationIsValid:Bool = Date().timeIntervalSince(location.timestamp) < maxAge && location.horizontalAccuracy <= requiredAccuracy;
if locationIsValid
{
NSLog(",,, location : %@",location);
NSLog("valid locations.....");
}
}

let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: locations[0].coordinate.latitude, longitude: locations[0].coordinate.longitude), span: MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005))
self.mapView.setRegion(region, animated: true)

CLGeocoder().reverseGeocodeLocation(manager.location!) { (placemarks, error) in
if error != nil{
print("Error: " + (error?.localizedDescription)!)
return
}
let pm = placemarks! as [CLPlacemark]
if pm.count > 0 {
let pm = placemarks![0]

let subThoroughfare = pm.subThoroughfare ?? ""
let thoroughfare = pm.thoroughfare ?? ""
let locality = pm.locality ?? ""
let administrativeArea = pm.administrativeArea ?? ""
let postalCode = pm.postalCode ?? ""
let country = pm.country ?? ""
let address = (subThoroughfare)+" "+(thoroughfare)+" "+(locality)+","+(administrativeArea)+" "+(postalCode)+" "+(country)

self.myAddress.text = "(address)"
}
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd, HH:mm:ss"
formatter.timeZone = NSTimeZone.local
let timestampFormattedStr = formatter.string(from: (locationManager.location?.timestamp)!)
let timeZone = NSTimeZone(forSecondsFromGMT: NSTimeZone.local.secondsFromGMT())
let timeZoneName = timeZone.localizedName(.standard, locale: NSLocale.current)
let timestampWithTimeZone = "(timestampFormattedStr) (String(describing: timeZoneName))"
let values = ["Time": timestampWithTimeZone,"Address": myAddress.text as Any]

let ref = Database.database().reference()
ref.child("userLocations").childByAutoId().setValue(values)
}


And below is the picture of my database
enter image description here










share|improve this question























  • At first time while reverseGeocodeLocation was decoding, you saved address into Firebase.

    – Surjeet
    Nov 21 '18 at 18:32











  • Call Firebase line inside reverseGeocodeLocation block, when received address. You problem will be fixed. Let me know, If you need any other help.

    – Surjeet
    Nov 21 '18 at 18:33













  • @Surjeet How to do that? Sorry I am new in this field.

    – Adam
    Nov 21 '18 at 18:51














1












1








1








I am trying to save user current location to firebase that include time and address. Basically, my code is working, but just the first location address always shows "label", not address. Therefore, when I re-run the app, it always has a label data in my firebase realtime database. I don't know how to fix it. I attached my code and the picture of my database below.



func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if locations.count > 0 {
let location = locations[locations.count-1]
let maxAge:TimeInterval = 60;
let requiredAccuracy:CLLocationAccuracy = 80;
let locationIsValid:Bool = Date().timeIntervalSince(location.timestamp) < maxAge && location.horizontalAccuracy <= requiredAccuracy;
if locationIsValid
{
NSLog(",,, location : %@",location);
NSLog("valid locations.....");
}
}

let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: locations[0].coordinate.latitude, longitude: locations[0].coordinate.longitude), span: MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005))
self.mapView.setRegion(region, animated: true)

CLGeocoder().reverseGeocodeLocation(manager.location!) { (placemarks, error) in
if error != nil{
print("Error: " + (error?.localizedDescription)!)
return
}
let pm = placemarks! as [CLPlacemark]
if pm.count > 0 {
let pm = placemarks![0]

let subThoroughfare = pm.subThoroughfare ?? ""
let thoroughfare = pm.thoroughfare ?? ""
let locality = pm.locality ?? ""
let administrativeArea = pm.administrativeArea ?? ""
let postalCode = pm.postalCode ?? ""
let country = pm.country ?? ""
let address = (subThoroughfare)+" "+(thoroughfare)+" "+(locality)+","+(administrativeArea)+" "+(postalCode)+" "+(country)

self.myAddress.text = "(address)"
}
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd, HH:mm:ss"
formatter.timeZone = NSTimeZone.local
let timestampFormattedStr = formatter.string(from: (locationManager.location?.timestamp)!)
let timeZone = NSTimeZone(forSecondsFromGMT: NSTimeZone.local.secondsFromGMT())
let timeZoneName = timeZone.localizedName(.standard, locale: NSLocale.current)
let timestampWithTimeZone = "(timestampFormattedStr) (String(describing: timeZoneName))"
let values = ["Time": timestampWithTimeZone,"Address": myAddress.text as Any]

let ref = Database.database().reference()
ref.child("userLocations").childByAutoId().setValue(values)
}


And below is the picture of my database
enter image description here










share|improve this question














I am trying to save user current location to firebase that include time and address. Basically, my code is working, but just the first location address always shows "label", not address. Therefore, when I re-run the app, it always has a label data in my firebase realtime database. I don't know how to fix it. I attached my code and the picture of my database below.



func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if locations.count > 0 {
let location = locations[locations.count-1]
let maxAge:TimeInterval = 60;
let requiredAccuracy:CLLocationAccuracy = 80;
let locationIsValid:Bool = Date().timeIntervalSince(location.timestamp) < maxAge && location.horizontalAccuracy <= requiredAccuracy;
if locationIsValid
{
NSLog(",,, location : %@",location);
NSLog("valid locations.....");
}
}

let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: locations[0].coordinate.latitude, longitude: locations[0].coordinate.longitude), span: MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005))
self.mapView.setRegion(region, animated: true)

CLGeocoder().reverseGeocodeLocation(manager.location!) { (placemarks, error) in
if error != nil{
print("Error: " + (error?.localizedDescription)!)
return
}
let pm = placemarks! as [CLPlacemark]
if pm.count > 0 {
let pm = placemarks![0]

let subThoroughfare = pm.subThoroughfare ?? ""
let thoroughfare = pm.thoroughfare ?? ""
let locality = pm.locality ?? ""
let administrativeArea = pm.administrativeArea ?? ""
let postalCode = pm.postalCode ?? ""
let country = pm.country ?? ""
let address = (subThoroughfare)+" "+(thoroughfare)+" "+(locality)+","+(administrativeArea)+" "+(postalCode)+" "+(country)

self.myAddress.text = "(address)"
}
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd, HH:mm:ss"
formatter.timeZone = NSTimeZone.local
let timestampFormattedStr = formatter.string(from: (locationManager.location?.timestamp)!)
let timeZone = NSTimeZone(forSecondsFromGMT: NSTimeZone.local.secondsFromGMT())
let timeZoneName = timeZone.localizedName(.standard, locale: NSLocale.current)
let timestampWithTimeZone = "(timestampFormattedStr) (String(describing: timeZoneName))"
let values = ["Time": timestampWithTimeZone,"Address": myAddress.text as Any]

let ref = Database.database().reference()
ref.child("userLocations").childByAutoId().setValue(values)
}


And below is the picture of my database
enter image description here







ios swift






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 21 '18 at 18:28









AdamAdam

416




416













  • At first time while reverseGeocodeLocation was decoding, you saved address into Firebase.

    – Surjeet
    Nov 21 '18 at 18:32











  • Call Firebase line inside reverseGeocodeLocation block, when received address. You problem will be fixed. Let me know, If you need any other help.

    – Surjeet
    Nov 21 '18 at 18:33













  • @Surjeet How to do that? Sorry I am new in this field.

    – Adam
    Nov 21 '18 at 18:51



















  • At first time while reverseGeocodeLocation was decoding, you saved address into Firebase.

    – Surjeet
    Nov 21 '18 at 18:32











  • Call Firebase line inside reverseGeocodeLocation block, when received address. You problem will be fixed. Let me know, If you need any other help.

    – Surjeet
    Nov 21 '18 at 18:33













  • @Surjeet How to do that? Sorry I am new in this field.

    – Adam
    Nov 21 '18 at 18:51

















At first time while reverseGeocodeLocation was decoding, you saved address into Firebase.

– Surjeet
Nov 21 '18 at 18:32





At first time while reverseGeocodeLocation was decoding, you saved address into Firebase.

– Surjeet
Nov 21 '18 at 18:32













Call Firebase line inside reverseGeocodeLocation block, when received address. You problem will be fixed. Let me know, If you need any other help.

– Surjeet
Nov 21 '18 at 18:33







Call Firebase line inside reverseGeocodeLocation block, when received address. You problem will be fixed. Let me know, If you need any other help.

– Surjeet
Nov 21 '18 at 18:33















@Surjeet How to do that? Sorry I am new in this field.

– Adam
Nov 21 '18 at 18:51





@Surjeet How to do that? Sorry I am new in this field.

– Adam
Nov 21 '18 at 18:51












2 Answers
2






active

oldest

votes


















1














The reverseGeocodeLocation block is asynchronous. This means your Firebase code happens before the block is called. When you assign self.myAddress you have already submitted to the database. To fix this put the firebase code inside the block.



if pm.count > 0 {
let pm = placemarks![0]

let subThoroughfare = pm.subThoroughfare ?? ""
let thoroughfare = pm.thoroughfare ?? ""
let locality = pm.locality ?? ""
let administrativeArea = pm.administrativeArea ?? ""
let postalCode = pm.postalCode ?? ""
let country = pm.country ?? ""
let address = (subThoroughfare)+" "+(thoroughfare)+" "+(locality)+","+(administrativeArea)+" "+(postalCode)+" "+(country)

self.myAddress.text = "(address)"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd, HH:mm:ss"
formatter.timeZone = NSTimeZone.local
let timestampFormattedStr = formatter.string(from: (locationManager.location?.timestamp)!)
let timeZone = NSTimeZone(forSecondsFromGMT: NSTimeZone.local.secondsFromGMT())
let timeZoneName = timeZone.localizedName(.standard, locale: NSLocale.current)
let timestampWithTimeZone = "(timestampFormattedStr) (String(describing: timeZoneName))"
let values = ["Time": timestampWithTimeZone,"Address": myAddress.text as Any]

let ref = Database.database().reference()
ref.child("userLocations").childByAutoId().setValue(values)
}
}





share|improve this answer































    0














    Follow this code:



    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {        
    manager.stopUpdatingLocation()
    if let location = locations.last {
    latitudeLabel.text = "Latitude: " + "(location.coordinate.latitude)"
    longitudeLabel.text = "Longitude: " + "(location.coordinate.longitude)"

    let geoCoder = CLGeocoder()
    geoCoder.reverseGeocodeLocation(location) { (placemarks, error) in
    if error != nil {
    print("Error found while reverse GEO coding.")
    return
    }

    if let placemark = placemarks?.first {
    var fullAddress = ""
    if let name = placemark.name {
    fullAddress.append("Name: " + name)
    }

    if let country = placemark.country {
    fullAddress.append("nCountry: " + country)
    }

    if let countryCode = placemark.isoCountryCode {
    fullAddress.append("nCountry code: " + countryCode)
    }

    if let locality = placemark.locality {
    fullAddress.append("nLocality: " + locality)
    }

    if let postal = placemark.postalCode {
    fullAddress.append("nPostal: " + postal)
    }

    if let thoroughfare = placemark.thoroughfare {
    fullAddress.append("nThoroughfare: " + thoroughfare)
    }

    if let administrativeArea = placemark.administrativeArea {
    fullAddress.append("nAdministrativeArea: " + administrativeArea)
    }

    if let subLocality = placemark.subLocality {
    fullAddress.append("nSubLocality: " + subLocality)
    }
    }
    }
    }
    }


    You have to stop update location.



    Hope you got your issue and this code will work for you.






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53418422%2fquestion-about-saving-user-current-location-into-database%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      The reverseGeocodeLocation block is asynchronous. This means your Firebase code happens before the block is called. When you assign self.myAddress you have already submitted to the database. To fix this put the firebase code inside the block.



      if pm.count > 0 {
      let pm = placemarks![0]

      let subThoroughfare = pm.subThoroughfare ?? ""
      let thoroughfare = pm.thoroughfare ?? ""
      let locality = pm.locality ?? ""
      let administrativeArea = pm.administrativeArea ?? ""
      let postalCode = pm.postalCode ?? ""
      let country = pm.country ?? ""
      let address = (subThoroughfare)+" "+(thoroughfare)+" "+(locality)+","+(administrativeArea)+" "+(postalCode)+" "+(country)

      self.myAddress.text = "(address)"
      let formatter = DateFormatter()
      formatter.dateFormat = "yyyy-MM-dd, HH:mm:ss"
      formatter.timeZone = NSTimeZone.local
      let timestampFormattedStr = formatter.string(from: (locationManager.location?.timestamp)!)
      let timeZone = NSTimeZone(forSecondsFromGMT: NSTimeZone.local.secondsFromGMT())
      let timeZoneName = timeZone.localizedName(.standard, locale: NSLocale.current)
      let timestampWithTimeZone = "(timestampFormattedStr) (String(describing: timeZoneName))"
      let values = ["Time": timestampWithTimeZone,"Address": myAddress.text as Any]

      let ref = Database.database().reference()
      ref.child("userLocations").childByAutoId().setValue(values)
      }
      }





      share|improve this answer




























        1














        The reverseGeocodeLocation block is asynchronous. This means your Firebase code happens before the block is called. When you assign self.myAddress you have already submitted to the database. To fix this put the firebase code inside the block.



        if pm.count > 0 {
        let pm = placemarks![0]

        let subThoroughfare = pm.subThoroughfare ?? ""
        let thoroughfare = pm.thoroughfare ?? ""
        let locality = pm.locality ?? ""
        let administrativeArea = pm.administrativeArea ?? ""
        let postalCode = pm.postalCode ?? ""
        let country = pm.country ?? ""
        let address = (subThoroughfare)+" "+(thoroughfare)+" "+(locality)+","+(administrativeArea)+" "+(postalCode)+" "+(country)

        self.myAddress.text = "(address)"
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd, HH:mm:ss"
        formatter.timeZone = NSTimeZone.local
        let timestampFormattedStr = formatter.string(from: (locationManager.location?.timestamp)!)
        let timeZone = NSTimeZone(forSecondsFromGMT: NSTimeZone.local.secondsFromGMT())
        let timeZoneName = timeZone.localizedName(.standard, locale: NSLocale.current)
        let timestampWithTimeZone = "(timestampFormattedStr) (String(describing: timeZoneName))"
        let values = ["Time": timestampWithTimeZone,"Address": myAddress.text as Any]

        let ref = Database.database().reference()
        ref.child("userLocations").childByAutoId().setValue(values)
        }
        }





        share|improve this answer


























          1












          1








          1







          The reverseGeocodeLocation block is asynchronous. This means your Firebase code happens before the block is called. When you assign self.myAddress you have already submitted to the database. To fix this put the firebase code inside the block.



          if pm.count > 0 {
          let pm = placemarks![0]

          let subThoroughfare = pm.subThoroughfare ?? ""
          let thoroughfare = pm.thoroughfare ?? ""
          let locality = pm.locality ?? ""
          let administrativeArea = pm.administrativeArea ?? ""
          let postalCode = pm.postalCode ?? ""
          let country = pm.country ?? ""
          let address = (subThoroughfare)+" "+(thoroughfare)+" "+(locality)+","+(administrativeArea)+" "+(postalCode)+" "+(country)

          self.myAddress.text = "(address)"
          let formatter = DateFormatter()
          formatter.dateFormat = "yyyy-MM-dd, HH:mm:ss"
          formatter.timeZone = NSTimeZone.local
          let timestampFormattedStr = formatter.string(from: (locationManager.location?.timestamp)!)
          let timeZone = NSTimeZone(forSecondsFromGMT: NSTimeZone.local.secondsFromGMT())
          let timeZoneName = timeZone.localizedName(.standard, locale: NSLocale.current)
          let timestampWithTimeZone = "(timestampFormattedStr) (String(describing: timeZoneName))"
          let values = ["Time": timestampWithTimeZone,"Address": myAddress.text as Any]

          let ref = Database.database().reference()
          ref.child("userLocations").childByAutoId().setValue(values)
          }
          }





          share|improve this answer













          The reverseGeocodeLocation block is asynchronous. This means your Firebase code happens before the block is called. When you assign self.myAddress you have already submitted to the database. To fix this put the firebase code inside the block.



          if pm.count > 0 {
          let pm = placemarks![0]

          let subThoroughfare = pm.subThoroughfare ?? ""
          let thoroughfare = pm.thoroughfare ?? ""
          let locality = pm.locality ?? ""
          let administrativeArea = pm.administrativeArea ?? ""
          let postalCode = pm.postalCode ?? ""
          let country = pm.country ?? ""
          let address = (subThoroughfare)+" "+(thoroughfare)+" "+(locality)+","+(administrativeArea)+" "+(postalCode)+" "+(country)

          self.myAddress.text = "(address)"
          let formatter = DateFormatter()
          formatter.dateFormat = "yyyy-MM-dd, HH:mm:ss"
          formatter.timeZone = NSTimeZone.local
          let timestampFormattedStr = formatter.string(from: (locationManager.location?.timestamp)!)
          let timeZone = NSTimeZone(forSecondsFromGMT: NSTimeZone.local.secondsFromGMT())
          let timeZoneName = timeZone.localizedName(.standard, locale: NSLocale.current)
          let timestampWithTimeZone = "(timestampFormattedStr) (String(describing: timeZoneName))"
          let values = ["Time": timestampWithTimeZone,"Address": myAddress.text as Any]

          let ref = Database.database().reference()
          ref.child("userLocations").childByAutoId().setValue(values)
          }
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 21 '18 at 21:28









          Steve O'ConnorSteve O'Connor

          1,035816




          1,035816

























              0














              Follow this code:



              func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {        
              manager.stopUpdatingLocation()
              if let location = locations.last {
              latitudeLabel.text = "Latitude: " + "(location.coordinate.latitude)"
              longitudeLabel.text = "Longitude: " + "(location.coordinate.longitude)"

              let geoCoder = CLGeocoder()
              geoCoder.reverseGeocodeLocation(location) { (placemarks, error) in
              if error != nil {
              print("Error found while reverse GEO coding.")
              return
              }

              if let placemark = placemarks?.first {
              var fullAddress = ""
              if let name = placemark.name {
              fullAddress.append("Name: " + name)
              }

              if let country = placemark.country {
              fullAddress.append("nCountry: " + country)
              }

              if let countryCode = placemark.isoCountryCode {
              fullAddress.append("nCountry code: " + countryCode)
              }

              if let locality = placemark.locality {
              fullAddress.append("nLocality: " + locality)
              }

              if let postal = placemark.postalCode {
              fullAddress.append("nPostal: " + postal)
              }

              if let thoroughfare = placemark.thoroughfare {
              fullAddress.append("nThoroughfare: " + thoroughfare)
              }

              if let administrativeArea = placemark.administrativeArea {
              fullAddress.append("nAdministrativeArea: " + administrativeArea)
              }

              if let subLocality = placemark.subLocality {
              fullAddress.append("nSubLocality: " + subLocality)
              }
              }
              }
              }
              }


              You have to stop update location.



              Hope you got your issue and this code will work for you.






              share|improve this answer




























                0














                Follow this code:



                func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {        
                manager.stopUpdatingLocation()
                if let location = locations.last {
                latitudeLabel.text = "Latitude: " + "(location.coordinate.latitude)"
                longitudeLabel.text = "Longitude: " + "(location.coordinate.longitude)"

                let geoCoder = CLGeocoder()
                geoCoder.reverseGeocodeLocation(location) { (placemarks, error) in
                if error != nil {
                print("Error found while reverse GEO coding.")
                return
                }

                if let placemark = placemarks?.first {
                var fullAddress = ""
                if let name = placemark.name {
                fullAddress.append("Name: " + name)
                }

                if let country = placemark.country {
                fullAddress.append("nCountry: " + country)
                }

                if let countryCode = placemark.isoCountryCode {
                fullAddress.append("nCountry code: " + countryCode)
                }

                if let locality = placemark.locality {
                fullAddress.append("nLocality: " + locality)
                }

                if let postal = placemark.postalCode {
                fullAddress.append("nPostal: " + postal)
                }

                if let thoroughfare = placemark.thoroughfare {
                fullAddress.append("nThoroughfare: " + thoroughfare)
                }

                if let administrativeArea = placemark.administrativeArea {
                fullAddress.append("nAdministrativeArea: " + administrativeArea)
                }

                if let subLocality = placemark.subLocality {
                fullAddress.append("nSubLocality: " + subLocality)
                }
                }
                }
                }
                }


                You have to stop update location.



                Hope you got your issue and this code will work for you.






                share|improve this answer


























                  0












                  0








                  0







                  Follow this code:



                  func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {        
                  manager.stopUpdatingLocation()
                  if let location = locations.last {
                  latitudeLabel.text = "Latitude: " + "(location.coordinate.latitude)"
                  longitudeLabel.text = "Longitude: " + "(location.coordinate.longitude)"

                  let geoCoder = CLGeocoder()
                  geoCoder.reverseGeocodeLocation(location) { (placemarks, error) in
                  if error != nil {
                  print("Error found while reverse GEO coding.")
                  return
                  }

                  if let placemark = placemarks?.first {
                  var fullAddress = ""
                  if let name = placemark.name {
                  fullAddress.append("Name: " + name)
                  }

                  if let country = placemark.country {
                  fullAddress.append("nCountry: " + country)
                  }

                  if let countryCode = placemark.isoCountryCode {
                  fullAddress.append("nCountry code: " + countryCode)
                  }

                  if let locality = placemark.locality {
                  fullAddress.append("nLocality: " + locality)
                  }

                  if let postal = placemark.postalCode {
                  fullAddress.append("nPostal: " + postal)
                  }

                  if let thoroughfare = placemark.thoroughfare {
                  fullAddress.append("nThoroughfare: " + thoroughfare)
                  }

                  if let administrativeArea = placemark.administrativeArea {
                  fullAddress.append("nAdministrativeArea: " + administrativeArea)
                  }

                  if let subLocality = placemark.subLocality {
                  fullAddress.append("nSubLocality: " + subLocality)
                  }
                  }
                  }
                  }
                  }


                  You have to stop update location.



                  Hope you got your issue and this code will work for you.






                  share|improve this answer













                  Follow this code:



                  func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {        
                  manager.stopUpdatingLocation()
                  if let location = locations.last {
                  latitudeLabel.text = "Latitude: " + "(location.coordinate.latitude)"
                  longitudeLabel.text = "Longitude: " + "(location.coordinate.longitude)"

                  let geoCoder = CLGeocoder()
                  geoCoder.reverseGeocodeLocation(location) { (placemarks, error) in
                  if error != nil {
                  print("Error found while reverse GEO coding.")
                  return
                  }

                  if let placemark = placemarks?.first {
                  var fullAddress = ""
                  if let name = placemark.name {
                  fullAddress.append("Name: " + name)
                  }

                  if let country = placemark.country {
                  fullAddress.append("nCountry: " + country)
                  }

                  if let countryCode = placemark.isoCountryCode {
                  fullAddress.append("nCountry code: " + countryCode)
                  }

                  if let locality = placemark.locality {
                  fullAddress.append("nLocality: " + locality)
                  }

                  if let postal = placemark.postalCode {
                  fullAddress.append("nPostal: " + postal)
                  }

                  if let thoroughfare = placemark.thoroughfare {
                  fullAddress.append("nThoroughfare: " + thoroughfare)
                  }

                  if let administrativeArea = placemark.administrativeArea {
                  fullAddress.append("nAdministrativeArea: " + administrativeArea)
                  }

                  if let subLocality = placemark.subLocality {
                  fullAddress.append("nSubLocality: " + subLocality)
                  }
                  }
                  }
                  }
                  }


                  You have to stop update location.



                  Hope you got your issue and this code will work for you.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 21 '18 at 18:36









                  iDev750iDev750

                  5961316




                  5961316






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53418422%2fquestion-about-saving-user-current-location-into-database%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      'app-layout' is not a known element: how to share Component with different Modules

                      android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

                      WPF add header to Image with URL pettitions [duplicate]