swiftios9core-locationcllocationmanagerclplacemark

swift - How to get my location data and put them in variables for iMessage?


Yesterday I asked a question here in stack Overflow about how to embed my current location in message body

I had got an answer and I corrected my code

My code works just fine in console, but i couldn't figure out how to get the data from displayLocationInfo function and store them in variables; then put variables in message body.

I'm sorta new in iPhone development

Any help ?

class Location: NSObject,CLLocationManagerDelegate {


    var locationManager = CLLocationManager()
    var currentLocation : CLPlacemark?
    var detectLocation : CLLocationManager?
    var locManager = CLLocationManager()


     func viewDidLoad()
    {
        viewDidLoad()

        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startUpdatingLocation()

    }


    func updateLocation()
    {
          locationManager.startUpdatingLocation()
    }



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


        CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in

            if (error != nil)
            {
                print("Error: " + error!.localizedDescription)
                return
            }

            if placemarks!.count > 0
            {
                let pm = placemarks![0]
                self.displayLocationInfo(pm)
            }
            else
            {
                print("Error with the data.")
            }
        })
    }

    func displayLocationInfo(placemark: CLPlacemark)
    {

        self.locationManager.stopUpdatingLocation()
        print(placemark.locality)
        print(placemark.postalCode)
        print(placemark.administrativeArea)
        print(placemark.country)
    }

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

}

Solution

  • import MessageUI
    

    make your class the correct delegate (this one is for iMessage):

    MFMessageComposeViewControllerDelegate
    

    make some global variables to store the fields you want to store (set them when you are printing to the console in your current code):

    class Location: NSObject,CLLocationManagerDelegate, MFMessageComposeViewControllerDelegate {
    
    
    var locationManager = CLLocationManager()
    var currentLocation : CLPlacemark?
    var detectLocation : CLLocationManager?
    var locManager = CLLocationManager()
    
    //put your variables for your message below:
    //you should use optionals (?) here but to keep it simple I'm assigning ""
    var locality = ""
    var postalCode = ""
    
    //set your variables when you are currently printing them in the console:
    func displayLocationInfo(placemark: CLPlacemark)
    {
    
        self.locationManager.stopUpdatingLocation()
        print(placemark.locality)
        print(placemark.postalCode)
        print(placemark.administrativeArea)
        print(placemark.country)
    
        //here I set postalcode to be used in the message later
        postalCode = placemark.postalCode
    
    }
    //call this function when the user hits a send button
    func messageAction() {        
        if MFMessageComposeViewController.canSendText() {
            let messageVC = MFMessageComposeViewController()
            messageVC.messageComposeDelegate = self    
            messageVC.body = "\(postalCode) is my postalCode"
            self.presentViewController(messageVC, animated: true, completion: nil)
        }
        else {
            print("User hasn't setup Messages.app")
        }
    }
    
    //if you have any code you want to run when the message is done sending put it in
    func messageComposeViewController(controller: MFMessageComposeViewController, didFinishWithResult result: MessageComposeResult) {
    
    self.dismissViewControllerAnimated(true, completion: nil)
    
        switch (result.rawValue) {
        case MessageComposeResultSent.rawValue:
            print("Message sent success")
        default:
            return
        }
    
    
    }
    

    Another option would be to make the messageAction() method have perameters that you include in your message. Like messageAction(postalCode: String?, locality: String?, municipality: String?) etc. It really depends on if you want to use these values in other methods globally or not.

    IN RESPONSE TO QUESTIONS FROM POSTER:

    Set a global variable (look in the large code sample above for this line). It makes postalCode a global variable.

    var postalCode = ""
    

    In displayLocationInfo() set this variable to have the location's value:

    postalCode = placemark.postalCode
    

    In messageAction() set the body of the message to use that variable:

    let messageVC = MFMessageComposeViewController()
    messageVC.body = "\(postalCode) is my postalCode"
    

    This will make a message that says "12345 is my postalCode" in the text message window.