jjzjj

iphone - CLLocationManager 委托(delegate)在初始化后不工作

coder 2023-09-24 原文

我正在尝试使用 rhomobile 框架让 iphone 的指南针工作。 我已经完成了 rhomobile 部分,创建了一个可在 iphone 上调用 native 方法的工作包装器,但我无法设法使事件正常工作。

位置管理器.h

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

@interface locationController : NSObject <CLLocationManagerDelegate> 
{
    CLLocationManager *locationManager;
}
@property (strong, nonatomic) CLLocationManager *locationManager;

- (id)init;
- (void)dealloc;

@end

位置管理器.m

#import "Locationmanager.h"

#include "ruby/ext/rho/rhoruby.h"

//store the values
double gx, gy, gz, gth;

//init location
locationController *lc;
@implementation locationController

@synthesize locationManager;

- (id)init {
if (self = [super init]) {
    self.locationManager = [[CLLocationManager alloc] init];

    NSLog(@"%@", [CLLocationManager headingAvailable]? @"\n\nHeading available!\n" : @"\n\nNo heading..\n");
    NSLog(@"%@", [CLLocationManager locationServicesEnabled]? @"\n\nLocation available!\n" : @"\n\nNo location..\n");

    // check if the hardware has a compass
    if ([CLLocationManager headingAvailable] == NO) {
        // No compass is available. This application cannot function without a compass, 
        // so a dialog will be displayed and no magnetic data will be measured.
        locationManager = nil;
        UIAlertView *noCompassAlert = [[UIAlertView alloc] initWithTitle:@"No Compass!" message:@"This device does not have the ability to measure magnetic fields." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [noCompassAlert show];
        [noCompassAlert release];
        NSLog(@"\n***** ERROR *****\n No compass found !!!");
    } else {
        // setup delegate callbacks
        locationManager.delegate = self;

        // heading service configuration
        locationManager.headingFilter = kCLHeadingFilterNone;

        // location service configuration
        locationManager.distanceFilter = kCLDistanceFilterNone;
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;

        //start location services
        [locationManager startUpdatingLocation];

        // start the compass
        [locationManager startUpdatingHeading];

    }
return self;
}
}
- (void)dealloc {    
    [super dealloc];
    // Stop the compass
    [locationManager stopUpdatingHeading];
    [locationManager release];
}

// This delegate method is invoked when the location manager has heading data.
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)heading {
    NSLog(@"\n\n***** New magnetic heading *****\n %f\n", heading.magneticHeading);
    NSLog(@"\n\n***** New true heading *****\n %f\n", heading.trueHeading);
    gx = heading.x;
    gy = heading.y;
    gz = heading.z;
    gth = heading.trueHeading;
}

// This delegate method is invoked when the location managed encounters an error condition.
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if ([error code] == kCLErrorDenied) {
        // This error indicates that the user has denied the application's request to use location services.
        NSLog(@"\n ***** ERROR *****\n Location not allowed!");
        [locationManager stopUpdatingHeading];
    } else if ([error code] == kCLErrorHeadingFailure) {
        NSLog(@"\n ***** ERROR *****\n Magnetic interference or something!");
    }
}

@end

//ruby wrappers
void locationmanager_init(void) {
   // make sure we can only start this method once
   static bool started = false;
   if(!started) {
       // Initialize the Objective C accelerometer class.
       lc = [[locationController alloc] init];
       started = true;
   }

}

void locationmanager_get_heading(double *x, double *y, double *z, double *th) {
    NSLog(@"\n ***** DEBUGGER *****\n Getting heading  x: %f, y: %f, z: %f, heading: %f", gx, gy, gz, gth);
    *x = gx;
    *y = gy;
    *z = gz;
    *th = gth;
}

我在装有 iOS 5.1 的 iphone 4 上运行代码,在控制台中我可以看到 init 的调试消息,但我从未看到 didUpdateHeading 委托(delegate)的调试消息。有人知道我在这里错过了什么吗?

更新

我认为我需要在后台线程中运行我的代码才能使其正常工作。目前 locationmanager_init 初始化 + 离开代码,因此它不活跃并且事件没有被触发。 任何人都有一个简单的解决方案,可以在后台初始化它以使其保持事件状态?

更新 2

返回了 id,使用了 self = [super init] 仍然没有修复 :(

GitHub code 使用 locationmanager_init 初始化,使用 locationmanager_get_heading 检索数据

最佳答案

你必须在主线程上初始化 CLLocationManager,检查这个 SO here ,或从具有事件运行循环的线程运行它,检查此 SO here , 来自 Apple 文档:

Configuration of your location manager object must always occur on a thread with 
an active run loop, such as your application’s main thread.

确保您的 locationController 和其中的 CCLocationManager 在初始化后仍然有效,检查 here .我在这里可能是错的,但从你的 Github 代码来看,似乎 *lc 变量在自动释放池中被释放。尝试给它额外的保留。

lc = [[[locationController alloc] init] retain];

我想这就是您遇到问题的原因。如果该对象已发布,您将不会获得任何更新。

与问题无关但是:

你应该最后而不是首先调用 [super dealloc],检查这个 SO here

将 return 语句放在最后一个括号之前的 init 方法中,而不是倒数第二个之前。

        ...
        // start the compass
        [locationManager startUpdatingHeading];

        }
    }
    return self;
}

关于iphone - CLLocationManager 委托(delegate)在初始化后不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12218118/

有关iphone - CLLocationManager 委托(delegate)在初始化后不工作的更多相关文章

  1. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  2. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  3. ruby-on-rails - 未初始化的常量 Psych::Syck (NameError) - 2

    在我的gem中,我需要yaml并且在我的本地计算机上运行良好。但是在将我的gem推送到ruby​​gems.org之后,当我尝试使用我的gem时,我收到一条错误消息=>"uninitializedconstantPsych::Syck(NameError)"谁能帮我解决这个问题?附言RubyVersion=>ruby1.9.2,GemVersion=>1.6.2,Bundlerversion=>1.0.15 最佳答案 经过几个小时的研究,我发现=>“YAML使用未维护的Syck库,而Psych使用现代的LibYAML”因此,为了解决

  4. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  5. ruby-on-rails - 未在 Ruby 中初始化的对象 - 2

    我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调

  6. ruby-on-rails - rspec should have_select ('cars' , :options => ['volvo' , 'saab' ] 不工作 - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion在首页我有:汽车:VolvoSaabMercedesAudistatic_pages_spec.rb中的测试代码:it"shouldhavetherightselect"dovisithome_pathit{shouldhave_select('cars',:options=>['volvo','saab','mercedes','audi'])}end响应是rspec./spec/request

  7. ruby-on-rails - s3_direct_upload 在生产服务器中不工作 - 2

    在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo

  8. ruby-on-rails - ActionController::RoutingError: 未初始化常量 Api::V1::ApiController - 2

    我有用于控制用户任务的Rails5API项目,我有以下错误,但并非总是针对相同的Controller和路由。ActionController::RoutingError:uninitializedconstantApi::V1::ApiController我向您描述了一些我的项目,以更详细地解释错误。应用结构路线scopemodule:'api'donamespace:v1do#=>Loginroutesscopemodule:'login'domatch'login',to:'sessions#login',as:'login',via::postend#=>Teamroutessc

  9. ruby - 这两个 Ruby 类初始化定义有什么区别? - 2

    我正在阅读一本关于Ruby的书,作者在编写类初始化定义时使用的形式与他在本书前几节中使用的形式略有不同。它看起来像这样:classTicketattr_accessor:venue,:datedefinitialize(venue,date)self.venue=venueself.date=dateendend在本书的前几节中,它的定义如下:classTicketattr_accessor:venue,:datedefinitialize(venue,date)@venue=venue@date=dateendend在第一个示例中使用setter方法与在第二个示例中使用实例变量之间是

  10. ruby - JetBrains RubyMine 3.2.4 调试器不工作 - 2

    使用Ruby1.9.2运行IDE提示说需要gemruby​​-debug-base19x并提供安装它。但是,在尝试安装它时会显示消息Failedtoinstallgems.Followinggemswerenotinstalled:C:/ProgramFiles(x86)/JetBrains/RubyMine3.2.4/rb/gems/ruby-debug-base19x-0.11.30.pre2.gem:Errorinstallingruby-debug-base19x-0.11.30.pre2.gem:The'linecache19'nativegemrequiresinstall

随机推荐