How to get the time zone name for a CLLocation

て烟熏妆下的殇ゞ 提交于 2019-12-06 10:41:50

You should use https://github.com/Alterplay/APTimeZones to get NSTimeZone from CLLocation. It also works with CLGeocoder.

since iOS9 it should be possible direclty using CLGeocoder as specified here: https://developer.apple.com/library/prerelease/ios/releasenotes/General/WhatsNewIniOS/Articles/iOS9.html

Search results for MapKit and CLGeocoder can provide a time zone for the result.

chris

I found an interesting approach using CLGeocoder, which I put into a category on CLLocation. The interesting part looks like this:

-(void)timeZoneWithBlock:(void (^)(NSTimeZone *timezone))block {        
    [[[CLGeocoder alloc] init] reverseGeocodeLocation:self completionHandler:^(NSArray *placemarks, NSError *error) {           
        NSTimeZone *timezone = nil;

        if (error == nil && [placemarks count] > 0) {               
            CLPlacemark *placeMark = [placemarks firstObject];
            NSString *desc = [placeMark description];

            NSRegularExpression  *regex  = [NSRegularExpression regularExpressionWithPattern:@"identifier = \"([a-z]*\\/[a-z]*_*[a-z]*)\"" options:NSRegularExpressionCaseInsensitive error:nil];
            NSTextCheckingResult *result = [regex firstMatchInString:desc options:0 range:NSMakeRange(0, [desc length])];

            NSString *timezoneString = [desc substringWithRange:[result rangeAtIndex:1]];

            timezone = [NSTimeZone timeZoneWithName:timezoneString];
        }
        block(timezone);            
    }];
}

Usage is like this:

CLLocation *myLocation = ...
[myLocation timeZoneWithBlock:^(NSTimeZone *timezone) {
    if (timezone != nil) {
        // do something with timezone
    } else {
        // error determining timezone
    }
}];

Despite requiring a network connection and working asynchronously, I have found this to be the most reliable way of getting the time zone for a location.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!