简体   繁体   English

在iOS 6/7的后台线程中获取用户的当前位置

[英]Getting users' current location in background thread for iOS 6/7

Hello i have a problem with getting users current location on iOS 6/7. 您好,我在获取用户在iOS 6/7上的当前位置时遇到问题。 I need users location on app startup but it takes 6-8 seconds to get users location, and until the location is retrieved the app doesn't hide the splash screen and that is not ok (for me). 我需要在应用启动时确定用户的位置,但是要获得用户位置需要6到8秒的时间,并且直到检索到该位置,该应用才不会隐藏启动屏幕,而且这对我来说也不行。

I wanted to get the users location in background using dispatch_async (GCD) but it did not change a thing :( . So i wanted to know is there a way to fi my problem. I really appreciate any help. Thanks in advance. Here is the code for init of my app: 我想使用dispatch_async(GCD)在后台获取用户位置,但是它并没有改变:(。所以我想知道有没有办法解决我的问题。我非常感谢您的帮助。在此先感谢。我的应用程序初始化代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

FinalMenuViewController *leftMenuViewController = [[FinalMenuViewController alloc] init];
MFSideMenuContainerViewController *container = [MFSideMenuContainerViewController
                                                containerWithCenterViewController:[self navigationController]
                                                leftMenuViewController:leftMenuViewController
                                                rightMenuViewController:nil];
container.panMode = MFSideMenuPanModeNone;
self.window.rootViewController = container;

if(([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)){
    [[UIBarButtonItem appearance] setTintColor:[UIColor whiteColor]];
}else{
    [[UIBarButtonItem appearance] setTintColor:[UIColor colorWithRed:(250.0/255.0) green:(139.0/255.0) blue:(40.0/255.0) alpha:1.0]];
}

[self.window makeKeyAndVisible];

[self displaySplashImage];

[self setDefaultData];

[self initLocationManager];

return YES;
}

-(void) displaySplashImage{

CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;

UIImage* myImage;
NSString *imgName = ([[UIScreen mainScreen] bounds].size.height == 568) ? @"Default-568h@2x.png" : @"Default.png";
myImage = [UIImage imageNamed:imgName];
self.splashView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.window.frame.size.width, self.window.frame.size.height)];

mainV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, screenHeight)];
[mainV addSubview:self.splashView];
[mainV setBackgroundColor: [UIColor clearColor]];

self.splashView.image = myImage;
self.splashView.contentMode = UIViewContentModeScaleAspectFit;

[self.window addSubview:mainV];
[self.window bringSubviewToFront:mainV];
[self removeImageView];

}
-(void) removeImageView{
if(mainV){
    [mainV removeFromSuperview];
}
}

--- EDIT ---- Here is the code for getting the current location ---编辑----这是获取当前位置的代码

-(void) initManager{
locManager_ = [[CLLocationManager alloc] init];
locManager_.delegate = self;
locManager_.distanceFilter = 50;
locManager_.desiredAccuracy = kCLLocationAccuracyBest;
[locManager_ startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_6_0){
CLLocation *loc = [locations lastObject];
GlobalVariables *vars = [GlobalVariables getInstance];
vars.currentLocatoin = loc;

}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
if ([error domain] == kCLErrorDomain) {
    switch ([error code]) {
        case kCLErrorDenied:{
            NSString *msg = @"ERROR_MSG_HERE";
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:msg delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
            [alert show];
            break;

        }
        case kCLErrorLocationUnknown:{
            NSString *msg = @"We were unable to find your location";
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:msg delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
            [alert show];
            break;
        }

        default:
            break;
    }
} else {

}
}

You can use dispatch_after to create a delay, and after the delay is finished, start executing code that requires the user location. 您可以使用dispatch_after创建一个延迟,并且在延迟完成后,开始执行需要用户位置的代码。 Here is a sample from my own code, where I subclass CLLocationManager and store the updated location in a private ivar (which is set inside the locationManager delegate method in my CLLocationManager subclass): 这是我自己的代码中的一个示例,其中,我子类化CLLocationManager并将更新的位置存储在私有ivar (该ivar在我的CLLocationManager子类的locationManager委托方法中设置):

(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation;

The updated location is then accessible through a getter ( getLastUpdatedUserLocation ). 然后可以通过getter( getLastUpdatedUserLocation )访问更新的位置。

Here's the code: 这是代码:

UserLocationManager* userLocationManager = [UserLocationManager sharedLocationManager];

    [userLocationManager requestAuthorizationAndStartUpdates];

    __block CLLocation* userLocation = [userLocationManager getLastUpdatedUserLocation];

    if(userLocation == nil){

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 6.00*NSEC_PER_SEC), dispatch_get_main_queue(), ^{

            userLocation = [userLocationManager getLastUpdatedUserLocation];


            NSLog(@"The user location after 6.00 secondss is lat: %f, long: %f",userLocation.coordinate.latitude,userLocation.coordinate.longitude);
        });
    }

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

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