iOS区域监控无法正常工作 [英] iOS Region Monitoring not working

查看:83
本文介绍了iOS区域监控无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经进行了几个月的iOS开发,最近我正在开发一个公交应用程序。
我目前正在模仿公交车的运行,并在公交车站上设置多个注释。出于测试目的,我仅设置了一个公交车站,并试图监视公交车何时进入该区域并退出。



奇怪的是,我的 didStartMonitoringForRegion 方法被完美调用,但 didEnterRegion didExitRegion 方法均未调用。每次我运行该程序时,公共汽车几乎都会通过停车而没有提示我。



有人可以向我解释为什么会发生这种情况以及如何解决吗? / p>

  let locationManager = CLLocationManager()
var allBusAnnotations = [MKPointAnnotation]()
var summitEastBusStations = [CLLocationCoordinate2D ]()
var busStopNames = [ Dix Stadium, Risman Plaza, Terrace Drive, Terrace Drive 2, C-Midway, Theatre Dr。, East Main Street, 南林肯]
var radius = 500 as CLLocationDistance

// 0.02是最佳放大倍数
var mapZoomInFactor:Double = 0.02

覆盖func viewDidLoad(){
super.viewDidLoad()
// //加载视图后,通常从笔尖进行其他任何设置。

self.getBusStop()
self.locationManager.delegate = self
//获取用户的确切位置
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
//仅在使用应用程序时获取用户的位置,而不在后台使用
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()

self。 mapView.showsUserLocation = true
self.setBusStopAnnotations(summitEastBusStations)
// self.mapView.mapType = MKMapType.Satellite
}
func locationManager(manager:CLLocationManager !, didUpdateLocations location: [[AnyObject]!){

//将纬度和经度发送到Apple服务器,然后返回地址
CLGeocoder()。reverseGeocodeLocation(manager.location,completeHandler:{(placeMarks:[ AnyObject] !,错误:NSError!)->如果错误!= $ n
{
println( Rever se Geocode失败: + error.localizedDescription)
return
}

如果placeMarks.count> 0
{
//获取最新位置
let pm = placeMarks.last as! CLPlacemark

让中心= CLLocationCoordinate2D(纬度:manager.location.coordinate.latitude,经度:manager.location.coordinate.longitude)

//在其中绘制一个圆地图将缩放至
let region = MKCoordinateRegion(center:center,span:MKCoordinateSpan(latitudeDelta:self.mapZoomInFactor,longitudeDelta:self.mapZoomInFactor))

self.mapView.setRegion(region,动画的:true)

self.displayLocationInfo(pm)

// self.distanceToClosestAnnotation(pm)

self.geoFencing()

//您可以忽略此部分。此问题无关紧要
var repeatTimes = 0
var count = 0
while(count< = 7)
{
if count ==(self.summitEastBusStations .count-1)
{
计数= 1
++ repeatTimes
}
否则,如果repeatTimes == 1
{
count = 0
++ repeatTimes
}
else if repeatTimes == 2
{
break
}

self.distanceToBusStop( pm,count:count)
++ count
}
}
})
}
func locationManager(manager:CLLocationManager !, didFailWithError错误:NSError !){
println( Location Manager Failed: + error.localizedDescription)
}

func locationManager(管理器:CLLocationManager !, didStartMonitoringForRegion区域:CLRegion!){
println(被监视的区域)
println(被监视的区域为\(region.description))
}

func locationManager(管理器:CLLocationManager!,monitoringDidFailForRegion区域:CLRegion !,带有错误错误:NSError!){
println(未能监视指定区域)
}

func locationManager(管理员:CLLocationManager !, didEnterRegion地区:CLRegion!){
println(公交车已进入该区域)
}

func locationManager(管理员:CLLocationManager !, didExitRegion地区:CLRegion!){
println(公共汽车离开了该区域)
}
func geoFencing()
{

let rismanPlaza = CLLocationCoordinate2D(纬度:41.1469492,经度:-81.344068)

var currentBusStop = CLLocation(纬度:rismanPlaza.latitude,经度:rismanPlaza.longitude)
addRadiusCircle (currentBusStop)

let busStopRegion = CLCircularRegion(center:CLLocationCoordinate2D(latitude:rismanPlaza.latitude,经度:rismanPlaza.longitude),radius:半径,标识符:busStopNames [1])$ ​​b
$ b如果radius> self.locationManager.maximumRegionMonitoringDistance
{
半径= self.locationManager.maximumRegionMonitoringDistance
}

locationManager.startMonitoringForRegion(busStopRegion)

}

//在指定位置附近创建半径
func addRadiusCircle(location:CLLocation)
{
self.mapView.delegate = self
var circle = MKCircle(centerCoordinate:location.coordinate,radius:radius)
self.mapView.addOverlay(circle)
}

//执行实际的圆形着色
func mapView (mapView:MKMapView!,rendererForOverlay覆盖图:MKOverlay!)-> MKOverlayRenderer!
{
如果overlay是MKCircle
{
var circle = MKCircleRenderer(overlay:overlay)
circle.strokeColor = UIColor.redColor()
circle。 fillColor = UIColor(红色:255,绿色:0,蓝色:0,alpha:0.1)
circle.lineWidth = 1
return circle
}
else
{
return nil
}
}


解决方案

我最终使用了 CLRegion.containsCoordinate(location.coordinate)方法。



对象进入我的设定区域后,它返回true,从这里我可以知道它何时进入和退出该区域。 / p>

I have been doing some iOS development for a couple of months and recently I am developing a bus app. I am currently mimicking the bus' movements and set up multiple annotations on the bus stops. For test purposes, I have setup just one bus stop and am trying to monitor when the bus has entered this region and exited as well.

Strangely, my didStartMonitoringForRegion method is called perfectly but neither the didEnterRegion nor didExitRegion methods are called. Every time I run the program, the bus pretty much passes the stop without prompting me so.

Could someone explain to me why this is happening and how to resolve it?

let locationManager = CLLocationManager()
var allBusAnnotations = [MKPointAnnotation]()
var summitEastBusStations = [CLLocationCoordinate2D]()
var busStopNames = ["Dix Stadium", "Risman Plaza", "Terrace Drive", "Terrace Drive 2","C-Midway","Theatre Dr.","East Main Street","South Lincoln"]
var radius = 500 as CLLocationDistance

// 0.02 is the best zoom in factor
var mapZoomInFactor : Double = 0.02

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

    self.getBusStop()
    self.locationManager.delegate = self
    // gets the exact location of the user
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    // gets the user's location only when the app is in use and not background
    self.locationManager.requestWhenInUseAuthorization()
    self.locationManager.startUpdatingLocation()

    self.mapView.showsUserLocation = true
    self.setBusStopAnnotations(summitEastBusStations)
    // self.mapView.mapType = MKMapType.Satellite  
}
    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {

    // sends the latitude and longitude to the Apple Servers then returns the address
    CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: { (placeMarks: [AnyObject]!, error: NSError!) -> Void in

        if error != nil
        {
            println("Reverse Geocode Failed: " + error.localizedDescription)
            return
        }

        if placeMarks.count > 0
        {
            // gets the most updated location
            let pm = placeMarks.last as! CLPlacemark

            let centre = CLLocationCoordinate2D(latitude: manager.location.coordinate.latitude, longitude: manager.location.coordinate.longitude)

            // draws a circle in which the map will zoom to
            let region = MKCoordinateRegion(center: centre, span: MKCoordinateSpan(latitudeDelta: self.mapZoomInFactor, longitudeDelta: self.mapZoomInFactor))

            self.mapView.setRegion(region, animated: true)

            self.displayLocationInfo(pm)

            // self.distanceToClosestAnnotation(pm)

            self.geoFencing()

            // YOU CAN IGNORE THIS WHOLE PART. IT'S IRRELEVANT FOR THIS QUESTION
            var repeatTimes = 0
            var count = 0 
            while(count <= 7)
            {
                if count == (self.summitEastBusStations.count - 1)
                {
                    count = 1
                    ++repeatTimes
                }
                else if repeatTimes == 1
                {
                    count = 0
                    ++repeatTimes
                }
                else if repeatTimes == 2
                {
                    break
                }

                self.distanceToBusStop(pm, count: count)
                ++count
            }
        }
    })
}
    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    println("Location Manager Failed: " + error.localizedDescription)
}

func locationManager(manager: CLLocationManager!, didStartMonitoringForRegion region: CLRegion!) {
    println("The region is monitored")
    println("The monitored region is \(region.description)")
}

func locationManager(manager: CLLocationManager!, monitoringDidFailForRegion region: CLRegion!, withError error: NSError!) {
    println("Failed to monitor the stated region")
}

func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) {
    println("The bus has entered the region")
}

func locationManager(manager: CLLocationManager!, didExitRegion region: CLRegion!) {
    println("The bus has left the region")
}
func geoFencing()
{

    let rismanPlaza = CLLocationCoordinate2D(latitude: 41.1469492, longitude: -81.344068)

    var currentBusStop = CLLocation(latitude: rismanPlaza.latitude, longitude: rismanPlaza.longitude)
    addRadiusCircle(currentBusStop)

    let busStopRegion = CLCircularRegion(center: CLLocationCoordinate2D(latitude: rismanPlaza.latitude, longitude: rismanPlaza.longitude), radius: radius, identifier: busStopNames[1])

    if radius > self.locationManager.maximumRegionMonitoringDistance
    {
        radius = self.locationManager.maximumRegionMonitoringDistance
    }

    locationManager.startMonitoringForRegion(busStopRegion)

}

// creates the radius around the specified location
func addRadiusCircle(location: CLLocation)
{
    self.mapView.delegate = self
    var circle = MKCircle(centerCoordinate: location.coordinate, radius: radius)
    self.mapView.addOverlay(circle)
}

// performs the actual circle colouring
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer!
{
    if overlay is MKCircle
    {
        var circle = MKCircleRenderer(overlay: overlay)
        circle.strokeColor = UIColor.redColor()
        circle.fillColor = UIColor(red: 255, green: 0, blue: 0, alpha: 0.1)
        circle.lineWidth = 1
        return circle
    }
    else
    {
        return nil
    }
}

解决方案

I ended up using the CLRegion.containsCoordinate(location.coordinate) method instead. It works pretty much the same way.

Once the object has entered my set region, it returns true and from here I can know when it's entered and exited the region.

这篇关于iOS区域监控无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆