【问题标题】:Location manager stops updating location位置管理器停止更新位置
【发布时间】:2017-05-30 13:38:47
【问题描述】:

我在更新用户位置时遇到了问题。我正在构建应用程序,它显示最近的垃圾桶以及它们与用户之间的距离。我正在使用这个位置管理器,但它从不更新位置。即使用户移动,存储的位置也保持不变

let manager = CLLocationManager()


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


    let location: CLLocation = locations.last!
    let myLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)

    //store myLocation in UserDefaults
    UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.set(myLocation.latitude, forKey: "latitude")
    UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.set(myLocation.longitude, forKey: "longitude")

    UserDefaults.standard.set(myLocation.latitude, forKey: "latitude")
    UserDefaults.standard.set(myLocation.longitude, forKey: "longitude")
    UserDefaults().synchronize()


    self.mapView.showsUserLocation = true

}

我用这个来计算距离

let myLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.value(forKey: "latitude") as! CLLocationDegrees, UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.value(forKey: "longitude") as! CLLocationDegrees)



    // geeft zin met afstand van locatie1 tot myLocation
    func afstandPuntTotUser(locatie1: CLLocationCoordinate2D) -> String {
        manager.startUpdatingLocation()
        let cllocatie1 = converter(locatie: locatie1)
        let myLocation = converter(locatie: myLocation)
        let afstand = cllocatie1.distance(from: myLocation)
        let afgerondeafstand = afstand - afstand.truncatingRemainder(dividingBy: 1.0)                                   //zorgt voor 1 kommagetal
        if afstand < 1000.0 {
            return "De afstand tot de bak is \(afgerondeafstand) meter"
        }
        else {
            return "De afstand tot de bak is \(afgerondeafstand / 1000 - (afgerondeafstand / 1000).truncatingRemainder(dividingBy: 0.1)) kilometer"
        }
    }

在应用程序内部,这不是一个很大的问题,但我需要不断更新位置才能使小部件正常工作。这个小部件显示了三个最近的垃圾桶,如果它使用旧的位置数据,它并没有真正做它应该做的事情。

这是我完整的 ViewController:

 import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {



@IBOutlet weak var mapView: MKMapView!

let manager = CLLocationManager()


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

    let location: CLLocation = locations[0]
    let myLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
    //let span: MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
    //let region: MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)

    //store myLocation in UserDefauls


    UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.set(myLocation.latitude, forKey: "latitude")
    UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.set(myLocation.longitude, forKey: "longitude")

    UserDefaults.standard.set(myLocation.latitude, forKey: "latitude")
    UserDefaults.standard.set(myLocation.longitude, forKey: "longitude")
    UserDefaults().synchronize()


    //region wel of niet? nog even over hebben
    //mapView.setRegion(region, animated: true)

    self.mapView.showsUserLocation = true
}





override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    manager.delegate = self
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.requestAlwaysAuthorization()
    manager.startUpdatingLocation()



    //maakt van CLLocationCoordinate een CLLocation
    func converter(locatie: CLLocationCoordinate2D) -> CLLocation {
        let latitude = locatie.latitude
        let longitude = locatie.longitude
        return CLLocation(latitude: latitude, longitude: longitude)
    }

    let myLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(UserDefaults.standard.value(forKey: "latitude") as! CLLocationDegrees, UserDefaults.standard.value(forKey: "longitude") as! CLLocationDegrees)

    //let myLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.value(forKey: "latitude") as! CLLocationDegrees, UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.value(forKey: "longitude") as! CLLocationDegrees)



    // geeft zin met afstand van locatie1 tot myLocation
    func afstandPuntTotUser(locatie1: CLLocationCoordinate2D) -> String {
        let cllocatie1 = converter(locatie: locatie1)
        let myLocation = converter(locatie: myLocation)
        let afstand = cllocatie1.distance(from: myLocation)
        let afgerondeafstand = afstand - afstand.truncatingRemainder(dividingBy: 1.0)                                   //zorgt voor 1 kommagetal
        if afstand < 1000.0 {
            return "De afstand tot de bak is \(afgerondeafstand) meter"
        }
        else {
            return "De afstand tot de bak is \(afgerondeafstand / 1000 - (afgerondeafstand / 1000).truncatingRemainder(dividingBy: 0.1)) kilometer"
        }
    }

    //geeft puur afstand van locatie1 tot myLocation
    func distanceForWidget(locatie1: CLLocationCoordinate2D) -> String {
        let cllocatie1 = converter(locatie: locatie1)
        let myLocation = converter(locatie: myLocation)
        let afstand = cllocatie1.distance(from: myLocation)
        let meters = afstand as Double - afstand.truncatingRemainder(dividingBy: 1.0) as Double
        let kilometers = afstand / 1000 - (afstand / 1000).truncatingRemainder(dividingBy: 0.1)
        if afstand < 1000.0 {
            return "\(meters) m"
        }
        else {
            return "\(kilometers) km"
        }

    }


    //voegt snel een afvalbakpin toe
    func addAfvalbak(pinLocatie: CLLocationCoordinate2D) -> MKAnnotation {
        return purePin(title: "Afvalbak", subtitle: afstandPuntTotUser(locatie1: pinLocatie), coordinate: pinLocatie) as MKAnnotation

    }

    //voegt sel een glasbakpin toe
    func addGlasbak(pinLocatie:CLLocationCoordinate2D) -> MKAnnotation {
        return purePin(title: "Glasbak", subtitle: afstandPuntTotUser(locatie1: pinLocatie), coordinate: pinLocatie)
    }

    //voegt snel een blikvangerpin toe
    func addBlikvanger(pinLocatie:CLLocationCoordinate2D) -> MKAnnotation {
        return purePin(title: "Blikvanger", subtitle: afstandPuntTotUser(locatie1: pinLocatie), coordinate: pinLocatie)
    }


    //voegt snel een volledige afvalbak pin + afstand toe
    func addFullAfvalbak(pinlocatie: CLLocationCoordinate2D) -> fullPin {
        return fullPin(title: "Afvalbak", subtitle: afstandPuntTotUser(locatie1: pinlocatie), coordinate: pinlocatie)
    }

    //voegt snel een volledige glasbak pin + afstand toe
    func addFullGlasbak(pinlocatie: CLLocationCoordinate2D) -> fullPin {
        return fullPin(title: "Glasbak", subtitle: afstandPuntTotUser(locatie1: pinlocatie), coordinate: pinlocatie)
    }

    //voegt snel een volledige blikvanger pin + afstand toe
    func addFullBlikvanger(pinlocatie: CLLocationCoordinate2D) -> fullPin {
        return fullPin(title: "Blikvanger", subtitle: afstandPuntTotUser(locatie1: pinlocatie), coordinate: pinlocatie)
    }







    //array met alle afvalbaklocaties
    let afvalbakLocaties: [CLLocationCoordinate2D] = [jacobbotkeweg1, jacobbotkeweg2, jacobbotkeweg3, jacobbotkeweg4, jacobbotkeweg5, jacobbotkeweg6, jacobbotkeweg7, aldlansdyk1, aldlansdyk2, aldlansdyk3, weideflora1, weideflora2, hempensweg1, hempensweg2, hempensweg3, hempensweg4, hempenserweg1, hempenserweg2, hempenserweg3, legedyk1, verlengdeschrans1, oostergoweg1, henridunantweg1, henridunantweg2, henridunantweg3, henridunantweg4, henridunantweg5, henridunantweg6, henridunantweg7, abbingapark1, abbingapark2, tijnjedyk1, tijnjedyk2, tijnjedyk3, tijnjedyk4, ipebrouwerssteeg1, nieuwestad1, nieuwestad2, nieuwestad3, nieuwestad4, nieuwestad5, nieuwestad6, nieuwestad7, nieuwestad8, nieuwestad9, nieuwestad10, nieuwestad11, nieuwestad12]

    //array met alle glasbaklocaties
    let glasbakLocaties: [CLLocationCoordinate2D] = [timothee1]

    //array met alle blikvangerlocaties
    let blikvangerLocaties: [CLLocationCoordinate2D] = [bitgummerdyk1]


    //slaat alle locaties op voor widget
    //UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.set(afvalbakLocaties, forKey: "afvalbakLocaties")
    //UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.set(glasbakLocaties, forKey: "glasbakLocaties")
    //UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.set(blikvangerLocaties, forKey: "blikvangerLocaties")



    //array met alle pinnen die worden toegevoegd
    var allePinnen: [MKAnnotation] = []

    //voegt alle afvalbakken toe aan allePinnen
    for item in afvalbakLocaties {
        allePinnen.append(addAfvalbak(pinLocatie: item))
    }

    //voegt alle glasbakken toe aan allePinnen
    for item in glasbakLocaties {
        allePinnen.append(addGlasbak(pinLocatie: item))
    }

    //voegt alle blikvangers toe aan allePinnen
    for item in blikvangerLocaties {
        allePinnen.append(addBlikvanger(pinLocatie: item))
    }


    //voegt alle pinnen toe aan de kaart
    mapView.addAnnotations(allePinnen)


    var fullPinnen:[fullPin] = []

    //voegt alle afvalbakken toe aan fullPinnen
    for item in afvalbakLocaties {
        fullPinnen.append(addFullAfvalbak(pinlocatie: item))
    }

    //voegt alle glasbakken toe aan fullPinnen
    for item in glasbakLocaties {
        fullPinnen.append(addFullGlasbak(pinlocatie: item))
    }

    //voegt alle blikvangers toe aan fullPinnen
    for item in blikvangerLocaties {
        fullPinnen.append(addFullBlikvanger(pinlocatie: item))
    }

    //sorteert de bakken in fullPinnen op afstand
    fullPinnen.sort {$0.afstand < $1.afstand}


    //slaat de 3 dichtsbijzijnde afvalbakken op
    UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")!.set(fullPinnen[0].afstand, forKey: "closestpin1afstand")
    UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.set(fullPinnen[0].title, forKey: "closestpin1naam")

    UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")!.set(fullPinnen[1].afstand, forKey: "closestpin2afstand")
    UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.set(fullPinnen[1].title, forKey: "closestpin2naam")

    UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")!.set(fullPinnen[2].afstand, forKey: "closestpin3afstand")
    UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.set(fullPinnen[2].title, forKey: "closestpin3naam")

    UserDefaults().synchronize()

【问题讨论】:

  • 可能你在调用这个方法。 manager.stopUpdatingLocation()
  • 我仔细检查过,但事实并非如此
  • 您是想在后台模式还是仅在前台模式下获取位置?
  • 背景和前景
  • 你在info.Plist中设置了值吗?

标签: swift3 core-location


【解决方案1】:

在同一个项目中创建一个新类并将此代码添加到您的新类中。然后检查您的 didUpdateLocations 方法是否会被调用。让我知道这段代码是否适合你。

@IBOutlet weak var mapView: MKMapView!

let manager = CLLocationManager()

   override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    manager.delegate = self
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.requestAlwaysAuthorization()
    manager.startUpdatingLocation()
    // Do any additional setup after loading the view, typically from a nib.
}

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

    let location: CLLocation = locations[0]
    let myLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
    //let span: MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
    //let region: MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)

    //store myLocation in UserDefauls


    UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.set(myLocation.latitude, forKey: "latitude")
    UserDefaults(suiteName: "group.Afvalbakfinder.Jordadema.userLocation")?.set(myLocation.longitude, forKey: "longitude")

    UserDefaults.standard.set(myLocation.latitude, forKey: "latitude")
    UserDefaults.standard.set(myLocation.longitude, forKey: "longitude")
    UserDefaults().synchronize()


    //region wel of niet? nog even over hebben
    //mapView.setRegion(region, animated: true)

    self.mapView.showsUserLocation = true
}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print("Failed to find user's location: \(error.localizedDescription)")
}

【讨论】:

  • 我发现了我的问题,我的位置正在更新,但新位置没有存储在 userdefaults 中
【解决方案2】:

检查以下内容:

  1. 在应用目标的功能部分中启用后台模式并选择位置更新。
  2. 在您的应用信息 plist 文件中添加 NSLocationUsageDescription。
  3. 如果您将在应用程序处于后台或未运行时使用定位服务,请在您的信息列表中添加隐私 - 始终使用位置描述,否则添加隐私 - 使用时的位置使用描述,如果您将只使用定位服务,而用户使用您的应用。

【讨论】:

  • 你是用模拟器测试的吗?
  • 模拟器和“现实生活”iPhone 6s
猜你喜欢
  • 1970-01-01
  • 2013-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-26
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多