gpt4 book ai didi

swift - map 在 Swift2 iOS9 中第一次不读取代码

转载 作者:行者123 更新时间:2023-11-28 13:03:51 25 4
gpt4 key购买 nike

我试图在我的 map 中显示一些商店并且它工作正常(用户第二次访问该 MapViewController,但第一次(当它要求用户许可位置时)它只显示用户位置和 map 未在用户位置“缩放”。

我要展示我的代码,它非常简单明了:

已更新新代码(它仍然无法正常工作,“didChangeAuthorizationStatus”未打印任何内容:

import UIKit
import MapKit

class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

let LoadURL = "http://www.website.es/shops.json"

var coordinates = CLLocation()

@IBOutlet weak var mapView:MKMapView!

var farmacia = [Farmacia]()

let locationManager = CLLocationManager()

var currentLocation = CLLocation()

var latitudeValor = String()

var longitudeValor = String()

override func viewDidLoad() {

super.viewDidLoad()

locationManager.delegate = self

// Request for a user's authorization for location services
locationManager.requestWhenInUseAuthorization()

if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
requestLocation()
}
}

func requestLocation () {

let status = CLLocationManager.authorizationStatus()

if status == CLAuthorizationStatus.AuthorizedWhenInUse || status == CLAuthorizationStatus.AuthorizedAlways {
self.mapView.showsUserLocation = true

var currentLocation = CLLocation()

print(locationManager.location)

if locationManager.location != nil
{
currentLocation = locationManager.location!
let center = CLLocationCoordinate2D(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

latitudeValor = String(currentLocation.coordinate.latitude)
longitudeValor = String(currentLocation.coordinate.longitude)

self.mapView.setRegion(region, animated: true)

requestPost()

mapView.delegate = self
}
}
}

func locationManager(locationManager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {

switch status {

case .NotDetermined:
self.locationManager.requestWhenInUseAuthorization()
break
case .AuthorizedWhenInUse:
self.locationManager.startUpdatingLocation()
requestLocation()
break
case .AuthorizedAlways:
self.locationManager.startUpdatingLocation()
requestLocation()
break
case .Restricted:
// restricted by e.g. parental controls. User can't enable Location Services
break
case .Denied:
// user denied your app access to Location Services, but can grant access from Settings.app
break
}
}

/*
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {

let location = locations.last as! CLLocation

let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)

let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

self.mapView.setRegion(region, animated: true)

requestPost()

mapView.delegate = self
}
*/

func requestPost () {

let myUrl = NSURL(string: "http://www.website.es/shops_by_position.php");

let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST"

let postString = "latitude="+latitudeValor+"&longitude="+longitudeValor
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

let session = NSURLSession.sharedSession()

let task = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in

// JSON RESULTADO ENTERO
//let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)!
//print("responseString = \(responseString)")

if error != nil
{
//print("error=\(error)")
return
}
else
{
self.farmacia = self.parseJsonData(data!)
}
}

task.resume()
}

func parseJsonData(data: NSData) -> [Farmacia] {

let farmacias = [Farmacia]()

do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary

// Parse JSON data
let jsonProductos = jsonResult?["farmacias"] as! [AnyObject]

//print(jsonProductos)

for jsonProducto in jsonProductos {

let farmacia = Farmacia()
farmacia.id = jsonProducto["id"] as! String
farmacia.nombre = jsonProducto["nombre"] as! String

farmacia.latitude = jsonProducto["latitude"] as! String
farmacia.longitude = jsonProducto["longitude"] as! String

let stringLat = NSString(string: farmacia.latitude)
let stringLon = NSString(string: farmacia.longitude)

let latitude: CLLocationDegrees = stringLat.doubleValue
let longitude: CLLocationDegrees = stringLon.doubleValue

coordinates = CLLocation(latitude: latitude,longitude: longitude)

let geoCoder = CLGeocoder()

geoCoder.reverseGeocodeLocation(coordinates, completionHandler: { placemarks, error in

if error != nil
{
//print(error)
return
}
else
{
if placemarks != nil && placemarks!.count > 0 {

let placemark = placemarks?[0]

// Add Annotation
let annotation = MKPointAnnotation()
annotation.title = farmacia.nombre
annotation.coordinate = placemark!.location!.coordinate

self.mapView.addAnnotation(annotation)
}

}

})
}
}
catch let parseError {
print(parseError)
}

return farmacias
}

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {

let identifier = "MyPin"

if annotation.isKindOfClass(MKUserLocation) {
return nil
}

let detailButton: UIButton = UIButton(type: UIButtonType.DetailDisclosure)

// Reuse the annotation if possible
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier)

if annotationView == nil
{
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "pin")
annotationView!.canShowCallout = true
annotationView!.image = UIImage(named: "pin.png")
annotationView!.rightCalloutAccessoryView = detailButton
}
else
{
annotationView!.annotation = annotation
}

return annotationView
}

func mapView(mapView: MKMapView, annotationView: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {

if control == annotationView.rightCalloutAccessoryView {
performSegueWithIdentifier("PinDetail2", sender: annotationView)
}
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "PinDetail" {
let destinationController = segue.destinationViewController as! FarmaciaDetailViewController
destinationController.titulo_farmacia = (sender as! MKAnnotationView).annotation!.title!
}
if segue.identifier == "PinDetail2" {
let destinationController = segue.destinationViewController as! FarmaciaWebDetailViewController
destinationController.nombre_farmacia = (sender as! MKAnnotationView).annotation!.title!
}
}

@IBAction func cancelToMap(segue:UIStoryboardSegue) {

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

我的问题是:为了在应用程序第一次请求许可并且用户选择"is"时显示用户位置缩放和我的商店条目,我必须更改什么?

这是我第一次使用 MapKit 框架,我有点迷茫,如果你能给我一些启发,我将不胜感激。

最佳答案

1)改变

class MapViewController: UIViewController, MKMapViewDelegate {

class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

2)改变

func locationManager(locationManager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {

switch status {

case .NotDetermined:
self.locationManager.requestAlwaysAuthorization()

        self.locationManager.requestWhenInUseAuthorization()

3) 添加NSLocationWhenInUseUsageDescription到Info.plist

enter image description here

编辑

4) 在viewDidLoad中添加如下代码

locationManager.delegate = self

编辑 2

5) 添加import到header

import CoreLocation

关于swift - map 在 Swift2 iOS9 中第一次不读取代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33277947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com