2014-09-29 79 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函數。

然後它應該顯示一個警報詢問使用位置服務的權限。