Stevic Stevic - 2 months ago 21
Swift Question

Print users coordinates when a button i pressed - Swift

how do I print users location when i press the "Share" button? Here is my code

As you can see I have a line/code thats prints out the coordinates, but if I want those coordinates print out when I press the share button instead. Can I do that and if, how?

Hope you understand what I mean.

I'm pretty new in Xcode and Swift!

import UIKit
import MapKit
import Firebase

class MapController: UICollectionViewController, UICollectionViewDelegateFlowLayout, CLLocationManagerDelegate, MKMapViewDelegate {


var window: UIWindow?
var mapView: MKMapView?
let locationManager = CLLocationManager()

let distanceSpan: Double = 500

var locationData: CLLocation!

let coordLabel = UILabel(frame: CGRectMake(10,100,400,50))


override func viewDidLoad() {
super.viewDidLoad()

navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Share", style: .Plain, target: self, action: #selector(share))


navigationItem.title = "Current Location"

self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.view.backgroundColor = UIColor.whiteColor()

self.mapView = MKMapView(frame: CGRectMake(0, 20, (self.window?.frame.width)!, (self.window?.frame.height)!))
self.view.addSubview(self.mapView!)

self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.mapView!.showsUserLocation = true


//Show User Location Button
let button: UIButton = UIButton(type: UIButtonType.Custom)
button.setImage(UIImage(named: "MyLocationButton"), forState: UIControlState.Normal)
button.addTarget(self, action: #selector(locationManagerButton), forControlEvents: UIControlEvents.TouchUpInside)
button.frame = CGRectMake(0, 0, 30, 30)
let barButton = UIBarButtonItem(customView: button)
self.navigationItem.leftBarButtonItem = barButton

// user is not logged in
if FIRAuth.auth()?.currentUser?.uid == nil {
performSelector(#selector(handleLogout), withObject: nil, afterDelay: 0)



}

view.addSubview(coordLabel)

}

func share() {

coordLabel.text = String(locationData.coordinate.longitude) + ", " + String(locationData.coordinate.latitude)

}


func handleLogout() {

do {
try FIRAuth.auth()?.signOut()
} catch let logoutError {
print(logoutError)
}

let loginController = LoginController()
presentViewController(loginController, animated: true, completion: nil)

}




func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
if let mapView = self.mapView {
let region = MKCoordinateRegionMakeWithDistance(newLocation.coordinate, self.distanceSpan, self.distanceSpan)
mapView.setRegion(region, animated: true)
mapView.showsUserLocation = true
}
}

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

let locationData = locations.last

let center = CLLocationCoordinate2D(latitude: locationData!.coordinate.latitude, longitude: locationData!.coordinate.longitude)

let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

self.mapView!.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()

let locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")




}

func locationManagerButton() {

mapView!.setCenterCoordinate(mapView!.userLocation.coordinate, animated: true)



}


func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
print("Errors: " + error.localizedDescription)
}


}

Answer

You will need a label that contains the outputted coordinates.

coordLabel = UILabel(frame: CGRectMake(10,100,400,50))
view.addSubview(coordLabel);

then you will need a global coordinate variable that gets updated on the delegated call. So, after let distanceSpan: Double = 500 put

var locationData: CLLocation!;

Then update the global value with in the delegate method...so instead oflocation = locations.last put locationData = locations.last and update the variable name elsewhere if needed.

Finally, output location data when needed.

func share(){
    coordLabel.text = String(locationData.coordinates.longitude) + ", " +   String(locationData.coordinates.latitude)
}

This is at first glance...you may run into some problems...keep me posted.