2015-09-28 120 views
0

我想要使用CLLocationManager以两个坐标的形式返回用户位置。CLLocationManager返回空值

  • 我想我有正确的授权(authorizedWhenInUse),但是当它会得到实际位置返回nil

  • 我也有NSLocationWhenInUseUsageDescription添加到我的plist

    import UIKit 
    import CoreLocation  
    class ViewController: UIViewController, CLLocationManagerDelegate { 
    // Create an instance of the CLLocationManager 
        var locManager = CLLocationManager() 
    
    // View did load function (run things inside of here) 
    override func viewDidLoad() { 
        super.viewDidLoad() 
        // Do any additional setup after loading the view, typically from a nib. 
    
        locManager.delegate = self 
        locManager.desiredAccuracy = kCLLocationAccuracyBest 
    
        // Check authorizationStatus 
        let authorizationStatus = CLLocationManager.authorizationStatus() 
        // List out all responses 
        switch authorizationStatus { 
        case .AuthorizedAlways: 
         println("authorized") 
        case .AuthorizedWhenInUse: 
         println("authorized when in use") 
        case .Denied: 
         println("denied") 
        case .NotDetermined: 
         println("not determined") 
        case .Restricted: 
         println("restricted") 
        } 
    
        // Get the location 
        locManager.startUpdatingLocation() 
    
        if(CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse){ 
         // Extract the location from CLLocationManager 
         let userLocation = locManager.location 
    
         // Check to see if it is nil 
         if userLocation != nil { 
          println("location is \(userLocation)") 
         } else { 
          println("location is nil") 
         } 
        } else { 
         println("not authorized") 
        } 
    
        } 
    } 
    
    override func didReceiveMemoryWarning() { 
        super.didReceiveMemoryWarning() 
        // Dispose of any resources that can be recreated. 
    } 
    

    }

回答

1

SDK中CLLocationManager.h头文件提供了有关 “.location” 属性这个提示:

Discussion: 
*  The last location received. Will be nil until a location has been received. 

要做的最好的事情是执行:

optional func locationManager(_ manager: CLLocationManager, 
     didUpdateLocations locations: [CLLocation]) 

委托方法,让你的位置离开那里,它被调用时,该设备的GPS解决,其中手机。

喜欢的东西:

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

    let userLocation = manager.location 

    print("location = \(userLocation.latitude) \(userLocation.longitude)") 

    } 
+0

我意识到,这将是零,如果位置还未确定,但是为什么'locManager.startUpdatingLocation()'不能提供位置? –

+0

确定位置需要花费几秒钟的时间。此外,您应该实现[“'locationManager(_:didFailWithError:)'”委托方法](https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManagerDelegate_Protocol/index.html#// apple_ref/occ/intfm/CLLocationManagerDelegate/locationManager:didFailWithError :)让你知道什么时候失败了(例如,用户没有给位置管理器使用权限?) –