我需要帮助来创建一个按钮,该按钮可以保存用户当前的位置以及其他位置(如果他们移动的话),因此我可以通过CSV文件导出这些位置

时间:2018-06-22 18:52:05

标签: ios iphone swift maps

因此,将当前位置的经度和纬度从我的locationManager函数传递到我的按钮函数时遇到了一些麻烦。我希望按钮可以将用户坐标存储在变量中,然后将该变量传递给我的任务类,以便我可以通过电子邮件将其导出为.csv文件。然后,该文件将被上传到我正在创建的地图上。 这是我的代码:

//
// ViewController.swift
// project
//
// Created by Tyler Struntz on 6/22/18.
// Copyright © 2018 Tyler Struntz. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
import MessageUI
class ViewController: UIViewController,CLLocationManagerDelegate
{
@IBAction func saveLocation(_ sender: Any)
{
}
@IBOutlet weak var map: MKMapView!
let locationManager = CLLocationManager()
//creating CSV file
var taskArr = [Task]()
var task: Task!
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let location = locations[0]
let span:MKCoordinateSpan = MKCoordinateSpanMake(0.0001, 0.0001)
let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
let _:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
self.map.showsUserLocation = true
let latCord = location.coordinate.latitude
let lonCord = location.coordinate.longitude
// print("--------------------\n")
// print("\(location.coordinate.latitude)")
// print("--------------------\n")
}
override func viewDidLoad()
{
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
////////////////////////////////////////
task = Task()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
}
class Task: NSObject
{
var name: String = ""
var latitude = Float("")
var longitude = Float("")
}

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

为什么不将myLocation定义为可选变量,例如

var myLocation:CLLocationCoordinate2D?

然后在 didUpdateLocations 函数中,您可以像

一样对其进行初始化
myLocation = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)   

在按钮中单击,您将获得以下代码:

if let location=myLocation {
   /* Code for saving the coordinates to CSV. Make sure to use location (or myLocation!) */
}