我目前正在开展一个项目,要求我在应用中获取用户位置。最初我把它编码为只显示一个工作的地图视图,但后来想让它显示用户的位置。我一直收到错误EXC_BAD_INSTRUCTION就行了
self.mapView.showsUserLocation = true
import UIKit
import MapKit
import CoreLocation
class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate
{
@IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Location Delegate Methods
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let center = CLLocationCoordinate2DMake(location!.coordinate.latitude, location!.coordinate.latitude)
let region = MKCoordinateRegion(center: center, span:MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1))
self.mapView.setRegion(region, animated: true)
self.locationManager.startUpdatingLocation()
}
答案 0 :(得分:0)
这可能会帮助你。
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate,NSURLConnectionDelegate,UITableViewDataSource,UITableViewDelegate{
let locationManager = CLLocationManager()
var latitude = 0.00;
var Longitude = 0.00;
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestLocation()
locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
// Do any additional setup after loading the view, typically from a nib.
}
@IBOutlet weak var myLabel: UILabel!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location11 = locations.first {
print("Found User's location: \(location11)")
print("Latitude: \(location11.coordinate.latitude) Longitude: \(location11.coordinate.longitude)")
latitude = location11.coordinate.latitude
Longitude = location11.coordinate.longitude
startConnection()
}
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Failed to find user's location: \(error.localizedDescription)")
}
}
在plist文件中添加权限。