Swift CLGeocoder 获取时区

标签 swift timezone completionhandler clgeocoder clplacemark

恐怕我的完成处理程序可能都搞砸了。我想做的是使用纬度和经度来获取时区。我希望整个函数返回 TimeZone 类型的值。以下代码有效,因为我可以获得正确的时区,但在返回阶段它崩溃了。

func getTimeZone(location: CLLocationCoordinate2D, completion: () -> TimeZone) -> TimeZone {
    
    var timeZone = TimeZone(identifier: "timeZone")
    var placemark: CLPlacemark?
    let cllLocation = CLLocation(latitude: location.latitude, longitude: location.longitude)
    let geocoder = CLGeocoder()
    
    geocoder.reverseGeocodeLocation(cllLocation) { placemarks, error in
        
        if let error = error {
            print(error.localizedDescription)
        } else {
            
            if let placemarks = placemarks {
                placemark = placemarks.first
            }
        }
        DispatchQueue.main.async {
            
            if let optTime = placemark?.timeZone {
                timeZone = optTime
            }

            return completion()
        }
    }
}

最佳答案

我认为完成实现有问题。尝试将其更改为这样的内容:

func getTimeZone(location: CLLocationCoordinate2D, completion: @escaping ((TimeZone) -> Void)) {
    let cllLocation = CLLocation(latitude: location.latitude, longitude: location.longitude)
    let geocoder = CLGeocoder()

    geocoder.reverseGeocodeLocation(cllLocation) { placemarks, error in

        if let error = error {
            print(error.localizedDescription)

        } else {
            if let placemarks = placemarks {
                if let optTime = placemarks.first!.timeZone {
                    completion(optTime)
                }
            }
        }
    }
}

然后你可以像这样调用该函数:

getTimeZone(location: CLLocationCoordinate2D(latitude: CLLocationDegrees(9.62), longitude: CLLocationDegrees(84.62))) { timeZone in
    print("Time zone: \(timeZone)")
}

关于Swift CLGeocoder 获取时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69499828/

相关文章:

ios - 应用关闭时点击 UILocalNotification

ios - Swift:自定义单元格中的 IBoutlets 为零

ios - Swift 2 中的替换字符串

timezone - 将时区 ID 存储在数据库中是否安全,或者它们可以更改吗?

xcode - Swift 从完成处理程序中显示 View Controller

ios - 从服务器获取数据时如何使用typealias

swift - 在 Swift 中动态引用 IBOutlet?

c - 如何在 Win32 C 中将 GMT 转换为本地时间?

powershell - 如何将 powershell UTC 日期时间对象转换为 EST

ios - 如何检查 HealthKit 功能何时完成(Swift)