2017-06-06 64 views
1

我想將我的經緯度傳遞給我的url參數,但返回零,但是當我在委託內打印時返回經度和緯度,我似乎無法找到問題,我已經嘗試了很多不同的方式和似乎沒有任何工作將CLLocationManager的經度和緯度傳遞給URL?

這是在哪裏存儲我的緯度和經度變量

var lat: Double! var long: Double!

這是我代表

func locationManager(_ manager:CLLocationManager, didUpdateLocations locations: [CLLocation]){ 

    currentLocation = manager.location!.coordinate 

    let locValue:CLLocationCoordinate2D = currentLocation! 

    self.long = locValue.longitude 
    self.lat = locValue.latitude 

    print(lat) 
    print(long) 

} 

和她Ë他們傳遞給我用了我的URL參數變量,但他們回到零,我不明白爲什麼

let userLat = String(describing: lat) 
let userLong = String(describing: long) 

謝謝

+0

確切位置在哪裏,你聲明''lat'and long'?你在哪裏試圖獲得他們的價值?你是否將委託分配給CLLocationManager實例? –

+0

我的課後,我沒有分配它的委託在視圖沒有加載 – SCS

回答

1

試着這麼做:

斯威夫特3

func locationManager(_ manager:CLLocationManager, didUpdateLocations locations: [CLLocation]){ 

    if let last = locations.last { 
     sendLocation(last.coordinate) 
    } 

} 

func sendLocation(_ coordinate: CLLocationCoordinate2D) { 
    let userLat = NSString(format: "%f", coordinate.latitude) as String 
    let userLong = NSString(format: "%f", coordinate.longitude) as String 

    // Run API Call.... 
} 
+0

我試過,但沒有工作,由於某種原因值不出來委託,如果我打印拉特委託外部它回升零 – SCS

+0

嘗試更新的答案 –

+0

得到它的工作,非常感謝你真的很感激你的幫助 – SCS

0

我想約瑟夫K的回答是不正確的。它捨棄了經緯度的值。它會像下面的代碼一樣。

let coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(exactly: 35.6535425)!, longitude: CLLocationDegrees(exactly: 139.7047917)!) 

let latitude = coordinate.latitude // 35.6535425 
let longitude = coordinate.longitude // 139.7047917 

let latitudeString = NSString(format: "%f", latitude) as String // "35.653543" 
let longitudeString = NSString(format: "%f", longitude) as String // "139.704792" 

所以正確的和簡單的代碼是:

斯威夫特3

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 

     guard let coordinate = locations.last?.coordinate else { return } 

     let latitude = "\(coordinate.latitude)" 
     let longitude = "\(coordinate.longitude)" 

     // Do whatever you want to make a URL. 
    } 
相關問題