如何在iOS中使用MKLocationManager(一个私有API)

3

我需要调用

[[MKLocationManager sharedLocationManager] _applyChinaLocationShift:newLocation]

在我的iOS应用中。

我认为MKLocationManager是一个私有类,似乎没有MapKit/MKLocationManager.h文件。

我不是针对App Store。有没有办法可以使用该私有API?

更新于2011-6-23

我真的需要答案,或者我可以反编译iOS SDK吗?

100声望几乎是我所有的。请帮帮我。


@WTP,我认为class-dump是某种反编译工具,对吧?我会去查一下的,也许我只需要生成类的声明,那样行吗? - Zhao Xiang
确实,它只会生成接口、协议和类别。 - user142019
@WTP,那我能用它做什么呢?我不知道该如何解决这个问题。 - Zhao Xiang
@WTP,我已经转储了所有MapKit的声明,但是我还是不知道我可以用它做什么。。 - Zhao Xiang
2个回答

10

如果上述答案对您不起作用,可能是因为整个类都是私有的(包括它的头文件)。这里介绍一种使用运行时技巧的替代方法;您必须确保签名是正确的,但我们可以使用一些防御性编码来避免崩溃。

首先,除非您只调用此方法一次,否则我建议将代码封装在一个帮助方法中:

// in some header file, you may want to give the method a prefix too
CLLocation *ApplyLocationManagerChinaLocationShift(CLLocation *newLocation);

现在,您可以使用NSClassFromString来获取类的引用,并使用performSelector执行方法。为了保险起见,我们可以先尝试确保该方法存在:

CLLocation *ApplyLocationManagerChinaLocationShift(CLLocation *newLocation)
{
  id sharedLocationManager = [NSClassFromString(@"MKLocationManager") performSelector:@selector(sharedLocationManager)];

  SEL theSelector = @selector(_applyChinaLocationShift:);

  // this will ensure sharedLocationManager is non-nil and responds appropriately
  if (![sharedLocationManager respondsToSelector:theSelector]) {
    return nil; // fail silently - check this in the caller
  }
  return [sharedLocationManager performSelector:theSelector withObject:newLocation];
}

我还没有运行上面的代码,但它应该能起作用。如果出于某种原因,@selector() 调用不起作用(我认为它们应该会起作用),那么你可以将它们替换为NSSelectorFromString()调用。


代码可以运行,但似乎_applyChinaLocationShift:只能用于CLLocationManager返回的位置。对于任意位置,它会返回nil。 - Anton

1

你可以简单地创建方法描述,从而在MKLocationManager上创建自己的类别。通过定义私有方法的外观,您使其可调用。但是,您必须确信它的签名正确,因为如果出错,您的应用程序将会崩溃。

这个类别可以放在自己的.h文件中,或者如果您只在一个地方使用它,则可以放在@implementation的正上方。

@interface MKLocationManager (china)
- (CLLocation *)_applyChinaLocationShift:(CLLocation *)newLocation;
@end

那么我写一个 MKLocationManager 类和 _applyChinaLocationShift: 方法的声明,gcc 将使用 SDK 中的实现? - Zhao Xiang
我遇到了一个编译错误:无法找到“MKLocationManager”的接口声明。我已经包含了#import "MapKit/MapKit.h"#import "CoreLocation/CoreLocation.h"。对我来说最大的问题是我不知道哪个.h文件中声明了MKLocationManager - Zhao Xiang
返回已翻译文本:签名应为- (CLLocation *)_applyChinaLocationShift:(CLLocation *)newLocation; - Zhao Xiang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接