swift - 如何获取我的位置数据并将它们放入 iMessage 的变量中?

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

昨天我在stack Overflow这里问了一个关于如何在消息正文中嵌入我当前位置的问题

我得到了答案并更正了我的代码

我的代码在控制台中工作得很好,但我不知道如何从 displayLocationInfo 函数获取数据并将它们存储在变量中;然后将变量放入消息正文中。

我是 iPhone 开发领域的新手

有什么帮助吗?

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)
    }

}
import MessageUI

让您的 class 成为正确的委托人(这个委托人用于 iMessage):

MFMessageComposeViewControllerDelegate

创建一些全局变量来存储您要存储的字段(在当前代码中打印到控制台时设置它们):

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
    }


}

另一种选择是使 messageAction() 方法具有包含在消息中的参数。比如 messageAction(postalCode: String?, locality: String?, municipality: String?) 等。这真的取决于你是否想在全局的其他方法中使用这些值。

回复发帖人的问题:

设置一个全局变量(查看上面这一行的大型代码示例)。它使 postalCode 成为全局变量。

var postalCode = ""

在 displayLocationInfo() 中将此变量设置为具有位置值:

postalCode = placemark.postalCode

在 messageAction() 中设置消息正文以使用该变量:

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

这将在短信中显示“12345 是我的邮政编码”window。