如何在swift中获取CLLocationManager的位置用户?

时间:2014-06-16 21:37:19

标签: ios swift core-location cllocationmanager

我的视图控制器上有这个代码,但这不起作用:

 import UIKit
 import CoreLocation
 class ViewController: UIViewController, CLLocationManagerDelegate {

  var location: CLLocationManager!

 override func viewDidLoad() {
    super.viewDidLoad()

    location=CLLocationManager()
    location.delegate = self
    location.desiredAccuracy=kCLLocationAccuracyBest
    location.startUpdatingLocation()
}

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

我对其他帖子中的阅读方式有所了解。但我没有得到永远,没有印刷品..

谢谢!

7 个答案:

答案 0 :(得分:19)

首先在plist文件中添加这两行

1)NSLocationWhenInUseUsageDescription

2)NSLocationAlwaysUsageDescription

然后这是类工作完成实现这个

import UIKit 
import CoreLocation

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {

var window: UIWindow?
var locationManager: CLLocationManager!
var seenError : Bool = false
var locationFixAchieved : Bool = false
var locationStatus : NSString = "Not Started"

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
    initLocationManager();
    return true
}

// Location Manager helper stuff
func initLocationManager() {
    seenError = false
    locationFixAchieved = false
    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.locationServicesEnabled
    locationManager.desiredAccuracy = kCLLocationAccuracyBest

    locationManager.requestAlwaysAuthorization()
}

// Location Manager Delegate stuff

func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    locationManager.stopUpdatingLocation()
    if (error) {
        if (seenError == false) {
            seenError = true
           print(error)
        }
    }
}

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

        println(coord.latitude)
        println(coord.longitude)
    }
}

func locationManager(manager: CLLocationManager!,
    didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        var shouldIAllow = false

        switch status {
        case CLAuthorizationStatus.Restricted:
            locationStatus = "Restricted Access to location"
        case CLAuthorizationStatus.Denied:
            locationStatus = "User denied access to location"
        case CLAuthorizationStatus.NotDetermined:
            locationStatus = "Status not determined"
        default:
            locationStatus = "Allowed to location Access"
            shouldIAllow = true
        }
        NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil)
        if (shouldIAllow == true) {
            NSLog("Location to Allowed")
            // Start location services
            locationManager.startUpdatingLocation()
        } else {
            NSLog("Denied access: \(locationStatus)")
        }
}
}

答案 1 :(得分:5)

以下是在Swift 3中获取用户位置的简单步骤

1)首先在带有描述

的plist文件中添加这一行
 NSLocationWhenInUseUsageDescription

2)在项目中添加CoreLocation.framework(在Build Phases-> Link Binary with Library)下

3)在AppDelegate类

   import CoreLocation

4)按如下方式创建locationManager对象

    var locationManager:CLLocationManager!

5)在didFinishLaunchingWithOptions

中编写以下代码
    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.distanceFilter = 200
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()

6)确认CLLocationManagerDelegate委托,如下所示

   class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate

7)编写CLLocationManagerDelegate委托方法以获取用户位置

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {

    print("location error is = \(error.localizedDescription)")

}


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

    let locValue:CLLocationCoordinate2D = (manager.location?.coordinate)!


    print("Current Locations = \(locValue.latitude) \(locValue.longitude)")
}

答案 2 :(得分:2)

由于您将位置声明为显式解包的可选项(CLLocationManager!),因此它需要初始化程序,无论是在jhurray建议的init方法中,还是内联,如下:

var location: CLLocationManager! = nil

请注意,您还有其他可能的问题,包括iOS 8对查询用户使用CoreLocation的权限有新的要求。有关详细信息,请参阅此question

答案 3 :(得分:2)

这与上面的代码相同,但截至本帖发布之日已清理为使用Swift。这对我有用。

赞赏原版海报。

(请注意,请将其粘贴到您将用于处理位置内容的任何课程中。)



var lastLocation = CLLocation()
var locationAuthorizationStatus:CLAuthorizationStatus!
var window: UIWindow?
var locationManager: CLLocationManager!
var seenError : Bool = false
var locationFixAchieved : Bool = false
var locationStatus : NSString = "Not Started"

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    
    
    self.initLocationManager()
    
}
    // Location Manager helper stuff
    func initLocationManager() {
        seenError = false
        locationFixAchieved = false
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        
        locationManager.requestAlwaysAuthorization()
    }
    
    // Location Manager Delegate stuff
    
    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
        locationManager.stopUpdatingLocation()
        if ((error) != nil) {
            if (seenError == false) {
                seenError = true
                print(error)
            }
        }
    }
    
    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        if (locationFixAchieved == false) {
            locationFixAchieved = true
            var locationArray = locations as NSArray
            var locationObj = locationArray.lastObject as CLLocation
            var coord = locationObj.coordinate
            
            println(coord.latitude)
            println(coord.longitude)
        }
    }
    
    func locationManager(manager: CLLocationManager!,  didChangeAuthorizationStatus status: CLAuthorizationStatus) {
            var shouldIAllow = false
            
            switch status {
            case CLAuthorizationStatus.Restricted:
                locationStatus = "Restricted Access to location"
            case CLAuthorizationStatus.Denied:
                locationStatus = "User denied access to location"
            case CLAuthorizationStatus.NotDetermined:
                locationStatus = "Status not determined"
            default:
                locationStatus = "Allowed to location Access"
                shouldIAllow = true
            }
            NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil)
            if (shouldIAllow == true) {
                NSLog("Location to Allowed")
                // Start location services
                locationManager.startUpdatingLocation()
            } else {
                NSLog("Denied access: \(locationStatus)")
            }
    }




答案 4 :(得分:0)

你需要有init函数。

覆盖init(编码器:)和init(nibName:bundle :)并添加您想要的任何自定义初始化。

因为您已经说过该位置不是可选的,所以必须在超级init调用所有init函数之前对其进行初始化。

func init() {
...
location = CLLocationManager()
// either set delegate and other stuff here or in viewDidLoad
super.init(nibName:nil, bundle:nil)
// other initialization below

}

答案 5 :(得分:0)

应该写成 func locationManager(manager:CLLocationManager,didUpdateLocations locations:[CLLocation]){

答案 6 :(得分:0)

在viewcontroller中执行以下操作[使用swift] -

  class ViewController:     
  UIViewController,MKMapViewDelegate,CLLocationManagerDelegate {


  var locationManager: CLLocationManager?
  var usersCurrentLocation:CLLocationCoordinate2D?

  override func viewDidLoad() {
    super.viewDidLoad()

    self.locationManager = CLLocationManager()

    if CLLocationManager.authorizationStatus() == .NotDetermined{
        locationManager?.requestAlwaysAuthorization()
    }

    locationManager?.desiredAccuracy = kCLLocationAccuracyBest
    locationManager?.distanceFilter = 200
    locationManager?.delegate = self
    startUpdatingLocation()

    usersCurrentLocation = CLLocationCoordinate2DMake(LATTITUDE, LONGITUDE)
    let span = MKCoordinateSpanMake(0.005, 0.005)
    let region = MKCoordinateRegionMake(usersCurrentLocation!, span)
    mapview.setRegion(region, animated: true)
    mapview.delegate = self
    mapview.showsUserLocation = true

}

// MARK:CLLocationManagerDelegate方法

func startUpdatingLocation() {
    self.locationManager?.startUpdatingLocation()
}

func stopUpdatingLocation() {
    self.locationManager?.stopUpdatingLocation()
}

// MARK:MKMapViewDelegate

func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation){
    mapview.centerCoordinate = userLocation.location!.coordinate
    mapview.showsUserLocation = true
    regionWithGeofencing()

}