我从中获取坐标,但我希望能够在位置管理器功能之外使用它们。是否可以使它们成为实例变量?如果是这样,有人可以给我一些示例代码吗?在下面的代码中,我在 func 内打印并且它可以工作,但我希望能够,例如在它之外打印,或者使用坐标。也许作为一个全局变量?我将如何编码?我无法从文档中完全理解。
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
var locationManager: CLLocationManager!
var seenError : Bool = false
var theSpan: MKCoordinateSpan = MKCoordinateSpanMake(0.1, 0.1)
var locationStatus : NSString = "Not Started"
var initialLoc:Int = 1
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.requestAlwaysAuthorization()
locationManager.delegate = self
var initialLoc:Int = 1
// Do any additional setup after loading the view, typically from a nib.
}
@IBOutlet weak var Map: MKMapView!
@IBAction func Here(sender: AnyObject) {
initLocationManager()
}
func initLocationManager() {
seenError = false
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.startUpdatingLocation()
Map.showsUserLocation = true
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var locationArray = locations as NSArray
var locationObj = locationArray.lastObject as CLLocation
var coord = locationObj.coordinate
if initialLoc == 1 {
var Region:MKCoordinateRegion = MKCoordinateRegionMake(coord, theSpan)
self.Map.setRegion(Region, animated:true)
initialLoc = 0
}
println(coord.latitude)
println(coord.longitude)
}
// Location Manager Delegate stuff
// If failed
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
locationManager.stopUpdatingLocation()
if (error) {
if (seenError == false) {
seenError = true
print(error)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}