简体   繁体   English

在iOS中获取当前位置的静态方法

[英]static way to get current location in iOS

I am new to iOS programming, and writing a practice app to do task based on user location. 我是iOS编程的新手,我写了一个练习应用程序来根据用户位置执行任务。

What I would like to have is to have a MyLocationManager wrapper class with a simple static function, something like 我想拥有一个带有简单静态函数的MyLocationManager包装器类,例如

+(CLLocation *) getCurrentLocation;

So it can be called universally. 因此可以被普遍称为。 However I found that usually the way to retrieve location is to implement the CLLocationManagerDelegate interface to have a succeed/fail handler, and usually the code is placed in the controller. 但是我发现通常检索位置的方法是实现CLLocationManagerDelegate接口以具有成功/失败处理程序,并且通常将代码放置在控制器中。

I am wondering if there's a suggested way to make such a centralized utility class like I mentioned, and wrap the retrieve location code nicely without having it exist in many different controllers? 我想知道是否存在建议的方法来制作这样的集中式实用程序类,并很好地包装检索位置代码,而又不存在于许多不同的控制器中?

IMO, what you want to archive is not the best practice. IMO,您要归档的不是最佳实践。 I think the tidiest way in this case is using block as a completion hander. 我认为在这种情况下,最简洁的方法是使用block作为完成处理程序。 It will look like this 看起来像这样

@implementation YourController

-(void)updateLocationAndDoSomething
{
    [Utilities startUpdateLocationWithCompletionHandler: ^ (CLLocationCoordinate2D location, BOOL *successed){
        //your custom code here
    }];
}
@end

here is a easy to understand tutorial about block http://www.appcoda.com/objective-c-blocks-tutorial/ in case you don't know how to 如果您不知道该如何做,这是一个有关块http://www.appcoda.com/objective-c-blocks-tutorial/的易于理解的教程

Second way, using delegation , your controller will look like this 第二种方法,使用delegation ,您的控制器将如下所示

@implementation YourController

-(void)gotLocationAndDoSomething:(CLLocationCoordinate2D) location
{
    //your custom code here
}

-(void)failedToGetLocation
{

}
@end

If you try to place them all into one Utility class, maybe it's possible in some cases, but it will get ugly very soon and hard to maintain. 如果尝试将它们全部放在一个Utility类中,则在某些情况下也许是有可能的,但是它将很快变得丑陋且难以维护。

Might not be the ideal way, but for now, store the variable in you're appDelgate and grab it from there whenever you need it. 可能不是理想的方法,但是现在,将变量存储在appDelgate中,并在需要时从那里获取它。

If you need to call the function more than once, then yes, crests a Utils class and put all the utilities/other methods there. 如果您需要多次调用该函数,那么可以,设置一个Utils类并将所有实用程序/其他方法放在此处。

Include the class where you need it and get your location. 在需要的地方包括课程,并获取您的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM