2014-09-29 64 views
2

用户位置这是我的代码:获得在迅速

import Foundation 
import CoreLocation 

class ViewController: UIViewController, CLLocationManagerDelegate { 

let locationManager = CLLocationManager() 

@IBOutlet weak var locationLabel: UILabel! 

var coord: CLLocationCoordinate2D? 

override func viewDidLoad() { 
    super.viewDidLoad() 
    locationManager.delegate = self 
    locationManager.desiredAccuracy = kCLLocationAccuracyBest 
    locationManager.requestWhenInUseAuthorization() 
    if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.Authorized { 
     locationManager.startUpdatingLocation() 
     println(coord!.longitude) 
     locationLabel.text = "location found" 
    } 

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { 
     var locationArray = locations as NSArray 
     var locationObj = locationArray.lastObject as CLLocation 
     coord = locationObj.coordinate 

    } 


    } 
} 

此代码不返回任何东西(它应该打印经度)。这似乎O.K因为如果我移动

  locationManager.startUpdatingLocation() 
     println(coord!.longitude) 

出来的if语句,Xcode中引发运行时错误,并说,它意外地发现零而展开的可选值。我不明白为什么?系统要求我允许我使用我的位置。

谢谢!

回答

3
override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
    locationManager = CLLocationManager() 
    locationManager.delegate = self 
    locationManager.desiredAccuracy = kCLLocationAccuracyBest 
    locationManager.requestAlwaysAuthorization() 
    locationManager.startUpdatingLocation() 
} 

func locationManager(manager:CLLocationManager, didUpdateLocations locations:AnyObject[] { 
    println("locations = \(locations)") 
    gpsResult.text = "success" 
} 
0

你在iOS8上运行?假设这样:

1.You需要后,初始化 self.locationManager = CLLocationManager()

2.右键,调用self.locationManager.requestAlwaysAuthorization();(前self.locationManager.delegate = self

3.添加这些键Info.plist中,使用外部文本编辑器(改变相应的文本)

<key>NSLocationWhenInUseUsageDescription</key> 
<string>This is needed for iOS8 and up (when in use)</string> 

<key>NSLocationAlwaysUsageDescription</key> 
<string>This is needed for iOS8 and up (always)</string> 

4.地方,你叫println(coord!.longitude)可能还为时过早。将其移入locationManager函数。

然后它应该显示一个警报询问使用位置服务的权限。