0

我有一个应用程序,可以按经度和纬度向我显示有关餐馆的信息。如何获取当前位置并将其放在 URL 中?这个想法是我按那个位置搜索,而不是按给定的坐标。

class Observer: ObservableObject {

@Published var  datas = [Datatype]()


init() {

    let url1 = "https://developers.zomato.com/api/v2.1/geocode?lat=\(latitude)8&lon=\(longitude)"
    let key = "c913841060ea614f7c0f5b5f120a21cb"
    //latitude = 33.4592298 - longitude = -70.645348

    print(url1)

  ...
4

1 回答 1

-1

这不是一个 Swift UI 问题,而是一个一般性的 Swift 问题。可以CLLocationManager用来获取用户的当前位置。一定CoreLocation要先导入。

import CoreLocation

...

init() {
    let latitude = CLLocationManager().location?.coordinate.latitude
    let longitude = CLLocationManager().location?.coordinate.longitude
    let url1 = "https://developers.zomato.com/api/v2.1/geocode?lat=\(latitude ?? 0.0)8&lon=\(longitude ?? 0.0)"
    let key = "c913841060ea614f7c0f5b5f120a21cb"
    //latitude = 33.4592298 - longitude = -70.645348

    print(url1)

  ...
}

您还必须确保获得用户访问其位置的权限。这需要NSLocationWhenInUseUsageDescription在您的 info.plist 中设置一个字符串值,该值说明您如何使用用户的位置。您可以通过 请求访问CLLocationManager().requestWhenInUseAuthorization()。您可以通过 来查看位置授权状态CLLocationManager.authorizationStatus()

于 2019-11-14T20:33:02.360 回答