2015-06-08 2 views
1

Я добавил библиотеку CoreLocation, а также NSLocationWhenInUseUsageDescription в info.plist, но когда я компилирую и запускаю, он не отображает текущее местоположение или не предлагает пользователю разрешить доступ к текущему местоположению. В настоящее время я имею следующее ниже, но он просто отображает все США. иCoreLocation Swift

The authorization status of location services is changed to: Not determined 

напечатан в журнале, но я не предложено разрешить доступ к текущему местоположению, ни я получаю предупреждение. Я пробовал логику и блок-схему здесь: Xcode warning when using MapKit and CoreLocation, но это не сработало.

import UIKit 
import MapKit 
import CoreLocation 

class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate{ 

var loadPoints:[Int: MapPointAnnotation] = [Int:MapPointAnnotation]() 
var map:MKMapView? 
var loads: [Load]? 
var rightButton: UIButton? 
var selectedLoad:Load? 
var manager:CLLocationManager! 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 


    // Core Location 
    manager = CLLocationManager() 
    manager.delegate = self 
} 


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

     print("The authorization status of location " + 
      "services is changed to: ") 

     switch CLLocationManager.authorizationStatus(){ 
     case .Denied: 
      println("Denied") 
     case .NotDetermined: 
      println("Not determined") 
     case .Restricted: 
      println("Restricted") 
     default: 
      println("Authorized") 
     } 

} 

func displayAlertWithTitle(title: String, message: String){ 
    let controller = UIAlertController(title: title, 
     message: message, 
     preferredStyle: .Alert) 

    controller.addAction(UIAlertAction(title: "OK", 
     style: .Default, 
     handler: nil)) 

    presentViewController(controller, animated: true, completion: nil) 

} 
override func viewDidAppear(animated: Bool) { 
    super.viewDidAppear(animated) 

    if CLLocationManager.locationServicesEnabled(){ 

     switch CLLocationManager.authorizationStatus(){ 
     case .Denied: 
      displayAlertWithTitle("Not Determined", 
       message: "Location services are not allowed for this app") 
     case .NotDetermined: 
      manager = CLLocationManager() 
      if let locationManager = self.manager{ 
       locationManager.delegate = self 
       locationManager.requestWhenInUseAuthorization() 
      } 
     case .Restricted: 
      displayAlertWithTitle("Restricted", 
       message: "Location services are not allowed for this app") 
     default: 
      println("Default") 
     } 

    } else { 

     println("Location services aren't enabled") 
    } 

} 

convenience init(frame:CGRect){ 
    self.init(nibName: nil, bundle: nil) 
    self.view.frame = frame 

    NSNotificationCenter.defaultCenter().addObserver(self, selector:"selectAnnotation:", name: "selectAnnotation", object: nil) 

    self.map = MKMapView(frame: frame) 
    self.map!.delegate = self 

    self.view.addSubview(self.map!) 
} 

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

    var userLocation:CLLocation = locations[0] as! CLLocation 
    var latitude:CLLocationDegrees = userLocation.coordinate.latitude 
    var longitude:CLLocationDegrees = userLocation.coordinate.longitude 
    var latDelta:CLLocationDegrees = 1.0 
    var lonDelta:CLLocationDegrees = 1.0 

    var span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta) 
    var location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude) 
    var region:MKCoordinateRegion = MKCoordinateRegionMake(location, span) 
    map!.setRegion(region, animated: true) 

} 

enter image description here enter image description here enter image description here

ответ

0

Во-первых, убедитесь, что у вас есть этот ключ в PLIST enter image description here

Во-вторых, запрос место службы в viewDidLoad, я испытываю с этим кодом

import UIKit 
import CoreLocation 

class ViewController: UIViewController,CLLocationManagerDelegate { 
var manager:CLLocationManager! 
override func viewDidLoad() { 
    super.viewDidLoad() 
    manager = CLLocationManager() 
    manager.delegate = self 
    if(NSString(string:UIDevice.currentDevice().systemVersion).doubleValue >= 8.0){ 
     manager.requestWhenInUseAuthorization() 
    } 
    // Do any additional setup after loading the view, typically from a nib. 
} 
func locationManager(manager: CLLocationManager!, 
    didChangeAuthorizationStatus status: CLAuthorizationStatus){ 

     print("The authorization status of location " + 
      "services is changed to: ") 

     switch CLLocationManager.authorizationStatus(){ 
     case .Denied: 
      println("Denied") 
     case .NotDetermined: 
      println("Not determined") 
     case .Restricted: 
      println("Restricted") 
     default: 
      println("Authorized") 
     } 

} 

И получить выход enter image description here

Вы должны запустить это на устройстве, и если вы не можете получить предупреждение, попробуйте удалить приложение, а затем снова запустить

+0

я попытался это. Это все еще не работает. –

+0

Я обновляю свой ответ, просто попробую – Leo

+0

Я пробовал обновленную версию, но она не работала, поэтому я обновил свой код и сделал снимок. –

Смежные вопросы