我正在尝试使用CoreLocation来获取iOS 8中的纬度和经度坐标。在浏览了很多帖子之后,我仍然不确定如何去做。此外,我将非常感谢locationManager()方法的简要说明,因为我不明白它们在获取位置时扮演的角色。我是否需要调用这些方法?因为我从未在任何例子中看到它们。
class ViewController: UIViewController, CLLocationManagerDelegate {
var locationMan = CLLocationManager()
var ourLocation: CLLocation!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.locationMan.delegate = self
self.locationMan.desiredAccuracy = kCLLocationAccuracyBest
self.locationMan.requestWhenInUseAuthorization()
self.locationMan.startUpdatingLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations : [AnyObject]!){
locationMan.stopUpdatingLocation()
ourLocation = locations[0] as! CLLocation
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println("Error: " + error.localizedDescription)
}
@IBAction func button(sender: AnyObject) {
var testClass:item = item()
在下一行之后,应用程序崩溃,我收到错误:致命错误:在展开Optional值时意外发现nil。我认为这意味着myLocation从未实际设置过。 (请注意,我正在进行浮动,因为我需要将该位置存储在我的服务器上)
testClass.lat = Float(ourLocation.coordinate.latitude)
println(testClass.lat)
testClass.long = Float(ourLocation.coordinate.longitude)
println(testClass.long)
testClass.name = "Nice"
testClass.description = "Wow this is pretty cool"
testClass.postItemToServer()
}
}
请注意,我已正确更新了我的plist文件!位置在模拟器中打开。
答案 0 :(得分:1)
检查传递给变量的值是否为nil
if ourLocation.coordinate.latitude != nil
{
testClass.lat = Float(ourLocation.coordinate.latitude)
println(testClass.lat)
}
同时检查经度。
答案 1 :(得分:1)
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate{
var manager:CLLocationManager!
var location : CLLocation!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.manager = CLLocationManager()
self.manager.delegate = self;
self.manager.desiredAccuracy = kCLLocationAccuracyBest
self.manager.requestWhenInUseAuthorization()
self.manager.startUpdatingLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations : [AnyObject]!){
manager?.stopUpdatingLocation()
self.location = locations[0] as CLLocation
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println("Error: " + error.localizedDescription)
}
@IBAction func button(sender: AnyObject) {
//check if location is not nil
if self.location != nil {
//assign your loaction values here
let lat = Float(location.coordinate.latitude)
let long = Float(location.coordinate.longitude)
} else {
println("locationManager.location is nil")
}
}
}
location属性是一个隐式解包的CLLocation可选,它可能是nil。除非你知道它不是零,否则你永远不应该访问隐式解包的可选成员。