Search code examples
xcodeswiftmfmessagecomposeviewcontrollercllocationcoordinate2d

how to send user longitude and latitude coordinates through sms text


Within my "share location" function, I want the user to have the ability to send a text that shares their current location in the form of long/lat coordinates. The error I get with what I have implemented is "Contextual type "string" cannot be used with array literal". How or what is the correct code to implement?

Here's my code

 @IBAction func shareLocation(sender: AnyObject) {
   // Send user coordinates through text

    if !MFMessageComposeViewController.canSendText() {
        print("SMS services are not available")

        var coordinate: CLLocationCoordinate2D

        messageVC!.body = [coordinate.latitude, coordinate.longitude];
        messageVC!.recipients = [LookoutCell.description()];
        messageVC!.messageComposeDelegate = self;


        self.presentViewController(messageVC!, animated: false, completion: nil)
    }
}

Solution

  • There's a lot wrong with this code:

    1. You're checking if you can't send a text via !MFMessageComposeViewController.canSendText(), and then sending if you can't (brackets need to end earlier)
    2. You declare var coordinate: CLLocationCoordinate2D without value, which won't compile
    3. Latitude and longitude are doubles, so you need string formatting to output these values
    4. body is a String, you were trying to send it an array.
    5. Try this instead: messageVC!.body = String(format: "Lat: %.4f, Long: %.4f", coordinate.latitude, coordinate.longitude) - you'll need to look into formatting guides for more detail (you could start here)