How to get the time zone name for a CLLocation

半城伤御伤魂 提交于 2020-01-02 20:12:24

问题


I have an application that uses a CLGeocoder to forwardGeocode a placemark from an address string. The CLPlacemark response contains a CLLocation which gives me GPS coordinates.

The only way to create an NSTimeZone seems to be by using the correct Time Zone Name. It is important to point out that I am not using the current location of the device, so [NSTimeZone localTimeZone] will not work for me.

Is there a way to get the timezone name for the CLLocation so that I can create an NSTimeZone correctly?

NOTE: I have been using timeZoneForSecondsFromGMT but that never contains correct DST data, so it is not helpful for me.


回答1:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/15417176/how-to-get-the-time-zone-name-for-a-cllocation

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