Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/122.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios CLGeocoder始终为纬度/经度返回零_Ios_Swift_Cllocation_Eventkit - Fatal编程技术网

Ios CLGeocoder始终为纬度/经度返回零

Ios CLGeocoder始终为纬度/经度返回零,ios,swift,cllocation,eventkit,Ios,Swift,Cllocation,Eventkit,我正在尝试获取纬度/经度坐标以用于基于位置的提醒(Eventkit) 地址是有效的,并且被正确地发送到函数,如果我为坐标提供了一个可选值,它将由函数ok返回,因此函数似乎可以工作,但地理编码器没有按照预期转换地址。 我不明白为什么不会 var lat: Double? var lon: Double? func getLocation(address: String) -> CLLocation { let geocoder = CLGeocoder() geocode

我正在尝试获取纬度/经度坐标以用于基于位置的提醒(Eventkit) 地址是有效的,并且被正确地发送到函数,如果我为坐标提供了一个可选值,它将由函数ok返回,因此函数似乎可以工作,但地理编码器没有按照预期转换地址。 我不明白为什么不会

var lat: Double?
var lon: Double?

func getLocation(address: String)  -> CLLocation {
    let geocoder = CLGeocoder()
    geocoder.geocodeAddressString(address) { placemarks, error in
        guard let placemark = placemarks?.first else { return }
        
        let coordinate = placemark.location?.coordinate
        lat = coordinate?.latitude //Is always nil
        lon = coordinate?.longitude //Is always nil
        
    }
    // Note: providing ?? sample coordinates in the return below works

    return CLLocation(latitude: lat!, longitude: lon!)
}

if self.locationChoice == "Dog's Home" {
    
    let address = "\(self.dog.addressLine1),\(self.dog.town),\(self.dog.postcode)"
    let structuredLocation = EKStructuredLocation(title: address)
    
    structuredLocation.geoLocation = getLocation(address: address)// asking for CLLocation
    structuredLocation.radius = 500
    let alarm = EKAlarm()
    if self.whenArrivingOrLeaving == 0 {
        alarm.proximity = EKAlarmProximity.enter
    }else {
        alarm.proximity = EKAlarmProximity.leave
    }
    alarm.structuredLocation = structuredLocation
    newReminder.addAlarm(alarm)
}

如果从异步方法返回一个值,那么应该使用补全

func getLocation(address: String,completion:@escaping(CLLocation? -> ())) {
     let geocoder = CLGeocoder()
     geocoder.geocodeAddressString(address) { placemarks, error in
           guard let placemark = placemarks?.first else { return } 
           completion(placemark.location)
     }

}
召唤


谢谢,使用print我可以看到lat Lon现在已返回。但是,我不知道如何从您键入的“Embedded all code here”(在此处嵌入所有代码)中获得结果,以便可以使用它?如果我把所有的代码都放在getLocation call中的newReminder.addAlarm(alarm)中,则不会将任何位置保存到提醒应用程序中。很抱歉不知道这一点,我才学了几个月,还有很长的路要走。:)如果你能解释这是如何做到的,我想这将为我打开许多新的大门。我已经将你的答案标记为正确(因为它是正确的),并且我的代码通过在getLocation调用中包含所有新的提醒代码来为不同的位置工作。这很好,但确实会导致代码重复,因此如果有一种方法可以将lat和lon从getLocation调用(scope)中去掉,那么就可以节省一些重复。但是谢谢你的帮助。
getLocation(address: address) { loc in 
   // embed all code here 
}