繁体   English   中英

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

[英]How to get Location user with CLLocationManager in swift?

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

  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"
 }

我有权限我在其他帖子中读到的内容。 但我没有得到永远,没有印刷品..

谢谢!!

首先在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)")
        }
}
}

以下是在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)")
}

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

var location: CLLocationManager! = nil

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

这与上面的代码相同,但在发布之日清理为使用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)") } } 

你需要有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

}

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

在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()

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM