2016-02-19 22 views
0

出於某種原因,我似乎無法獲取用戶位置。我買了iOS 9食譜和應付他們的代碼完全CoreLocation的問題

這裏是視圖控制器:

import UIKit 
import CoreLocation 

class ViewController: UIViewController, CLLocationManagerDelegate { 

lazy var locationManager: CLLocationManager = { 
    let m = CLLocationManager() 
    m.delegate = self 
    m.desiredAccuracy = kCLLocationAccuracyNearestTenMeters 
    return m 
}() 

func locationManager(manager: CLLocationManager, 
    didUpdateLocations locations: [CLLocation]) { 
    //TODO: now you have access to the location. do your work 
} 

func locationManager(manager: CLLocationManager, 
    didFailWithError error: NSError) { 
    //TODO: handle the error 
} 

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

    if case .AuthorizedWhenInUse = status{ 
    manager.requestLocation() 
    } else { 
    //TODO: we didn't get access, handle this 
    print("No Access Granted") 
    } 

} 

@IBAction func requestLocation() { 

    locationManager.requestWhenInUseAuthorization() 

} 

} 

在控制檯輸出爲:

沒有準許訪問

任何想法是怎麼回事?我已經在模擬器和設備上進行了測試

編輯:我在故事板中添加了一個按鈕,並相應地將它舔到了IBAction。

回答

1

您是否已將NSLocationWhenInUseUsageDescription鑰匙添加到您的plist中? - 該值應該是一個字符串,描述您想要使用用戶位置的原因。

<key>NSLocationWhenInUseUsageDescription</key> 
<string>Required to provide information about your location.</string> 

如果它的所有工作正常的didUpdateLocations委託方法應返回的位置陣列,可以打印出這些,像這樣......

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    for loc in locations { 
     print(loc) 
    } 
} 

如果你想持續監控的位置,你可以撥打manager.startUpdatingLocation()代替manager.requestLocation()

+0

噢謝謝。該部分在該書的另一段中。我會在6分鐘內接受這個問題,當它讓我:) – JamesG

+0

沒問題,與那些'CLLocations'玩! – Wez

+0

我不假設你會知道,使用上面的代碼我將如何打印Users位置?本節以上面的代碼停止,所以有一點卡住:/ – JamesG