Swift3 位置管理器停止更新位置

Swift3 位置管理器停止更新位置,swift3,core-location,Swift3,Core Location,我在更新用户位置时遇到问题。我正在构建一个应用程序,显示最近的垃圾桶以及它们与用户之间的距离。我正在使用此locationmanager,但它从不更新位置。即使用户移动,存储的位置也保持不变 let manager = CLLocationManager() func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location: C

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

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"
        }
    }
让myLocation:CLLocationCoordinate2D=CLLocationCoordinate2DMake(用户默认值(suiteName:“group.Afvalbakfinder.Jordadema.userLocation”)?.value(forKey:“latitude”)为!CLLocationDegrees,UserDefault(suiteName:“group.Afvalbakfinder.Jordadema.userLocation”)?.value(forKey:“经度”)为!CLLocationDegrees)
//geeft zin在我的位置上遇到了一辆客货两用车
func AFSTANDPUNTOTOTUTUSER(位置1:CLLocationCoordinate2D)->字符串{
经理:startUpdatingLocation()
设cllocatie1=转换器(位置:位置1)
设myLocation=转换器(位置:myLocation)
让afstand=cllocatie1.距离(从:myLocation)
让afgerodeafstand=afstand-afstand.truncingRestricts(dividingBy:1.0)//zorgt voor 1 kommagetal
如果afstand<1000.0{
返回“待命总人数为\(待命)米”
}
否则{
return“deafstand tot De bak为\(afgeronedeafstand/1000-(afgeronedeafstand/1000)。截断剩余(除以:0.1))公里”
}
}
在应用程序内部,这不是一个很大的问题,但我需要一个不断更新的位置,以便小部件正常工作。这个小部件显示了三个最近的垃圾桶,如果它使用的是旧的位置数据,它不会真正做它应该做的事情

这是我的完整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()
导入UIKit
导入地图套件
导入核心定位
类ViewController:UIViewController、CLLocationManagerDelegate{
@ibvar映射视图:MKMapView!
let manager=CLLocationManager()
func locationManager(manager:CLLocationManager,didUpdateLocations位置:[CLLocation]){
let位置:CLLocation=位置[0]
让myLocation:CLLocationCoordinate2D=CLLocationCoordinate2DMake(location.coordinate.latitude,location.coordinate.longitude)
//让span:MKCoordinateSpan=MKCoordinateSpan-make(0.01,0.01)
//let区域:MKCoordinateRegion=MKCoordinateRegionMake(myLocation,span)
//将myLocation存储在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()
//尼特诺格地区的福利甚至超过了赫本
//mapView.setRegion(区域,动画:true)
self.mapView.showsUserLocation=true
}
重写func viewDidLoad(){
super.viewDidLoad()
//加载视图后,通常从nib执行任何其他设置。
manager.delegate=self
manager.desiredAccuracy=KCallocationAccuracyBest
manager.requestAlwaysAuthorization()
经理:startUpdatingLocation()
//maakt van CLLocation坐标和位置
func转换器(位置:CLLocationCoordinate2D)->CLLocation{
让纬度=位置纬度
让经度=位置经度
返回位置(纬度:纬度,经度:经度)
}
让myLocation:CLLocationCoordinate2D=CLLocationCoordinate2DMake(UserDefaults.standard.value(forKey:“latitude”)为!CLLocationDegrees,UserDefaults.standard.value(forKey:“经度”)为!CLLocationDegrees)
//让myLocation:CLLocationCoordinate2D=CLLocationCoordinate2DMake(用户默认值(suiteName:“group.Afvalbakfinder.Jordadema.userLocation”)?.value(forKey:“latitude”)为!CLLocationDegrees,UserDefault(suiteName:“group.Afvalbakfinder.Jordadema.userLocation”)?.value(forKey:“经度”)为!CLLocationDegrees)
//geeft zin在我的位置上遇到了一辆客货两用车
func AFSTANDPUNTOTOTUTUSER(位置1:CLLocationCoordinate2D)->字符串{
设cllocatie1=转换器(位置:位置1)
设myLocation=转换器(位置:myLocation)
让afstand=cllocatie1.距离(从:myLocation)
让afgerodeafstand=afstand-afstand.truncingRestricts(dividingBy:1.0)//zorgt voor 1 kommagetal
如果afstand<1000.0{
返回“待命总人数为\(待命)米”
}
否则{
return“deafstand tot De bak为\(afgeronedeafstand/1000-(afgeronedeafstand/1000)。截断剩余(除以:0.1))公里”
}
}
//geeft puur afstand van locatie1 tot myLocation
func distanceForWidget(位置1:CLLocationCoordinate2D)->字符串{
设cllocatie1=转换器(位置:位置1)
设myLocation=转换器(位置:myLocation)
让afstand=cllocatie1.距离(从:myLocation)
让meters=afstand作为Double-afstand。截断余数(dividingBy:1.0)作为Double
设km=afstand/1000-(afstand/1000)。截断余数(除数:0.1)
如果afstand<1000.0{
返回“\(米)m”
}
否则{
返回“\(公里)公里”
}
}
//沃格特·斯奈尔(voegt snel-een-afvalbakpin)脚趾
func addAfvalbak(pinLocatie:CLLocationCoordinate2D)->MKAnnotation{
返回purePin(标题:“Afvalbak”,副标题:AfStandPuntotTuser(位置1:pinLocatie),坐标:pinLocatie)作为MKAnnotation
}
//voegt Seleen glasbakpin脚趾
func addGlasbak(pinLocatie:CLLocationCoordinate2D)->MKAnnotation{
返回purePin(标题:“Glasbak”,副标题:AFStandPuntotTuser(位置1:pinLocatie),坐标:pinLocatie)
}
//我的脚很软
func
@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)")
}