這個問題在這里已經有了答案: SwiftUI 加載資料 (1 個回答) 昨天關閉。
我正在嘗試使用用戶的當前位置在應用程式啟動時呼叫 API。我目前的代碼是:
在ContentView.swift 中:
struct ContentView: View {
@StateObject var locationManager = LocationManager()
var userLocation: String {
let latitude = "\(locationManager.lastLocation?.coordinate.latitude ?? 0)"
let longitude = "\(locationManager.lastLocation?.coordinate.longitude ?? 0)"
return "\(latitude),\(longitude)"
}
@ObservedObject var api = randomAPI(location: userLocation)
var body: some View {
...
在randomAPI.swift 中:
class randomAPI: ObservableObject {
init(location: String) {
callAPI(userLocation: location)
}
func callAPI(userLocation: String) {
...
我收到錯誤:
無法在屬性初始值設定項中使用實體成員“userLocation”;屬性初始值設定項在 'self' 可用之前運行。
我不知道我應該在哪里放置下面的行來初始化 randomAPI。(實際上我什至不知道這是否是初始化它的正確方法 LOL)
@ObservedObject var api = randomAPI(location: userLocation)
有人可以幫我解決這個問題嗎?謝謝!
uj5u.com熱心網友回復:
正如Joakim提到的,您需要使用.onAppear. 這是因為在結構中設定屬性之前您無法訪問該屬性。
對于您的情況,代碼如下所示:
struct ContentView: View {
@StateObject var locationManager = LocationManager()
var userLocation: String {
let latitude = "\(locationManager.lastLocation?.coordinate.latitude ?? 0)"
let longitude = "\(locationManager.lastLocation?.coordinate.longitude ?? 0)"
return "\(latitude),\(longitude)"
}
@ObservedObject var api: randomAPI?
var body: some View {
SomeView()
.onAppear {
api = randomAPI(location: userLocation)
}
...
但是,我不認為ObservedObject在視圖出現后設定一個權限是最好的方法。
如果我是你,我會洗掉類中的 init 方法rapidAPI:
class randomAPI: ObservableObject {
func callAPI(userLocation: String) {
...
并callAPI在視圖出現時呼叫該方法:
struct ContentView: View {
@StateObject var locationManager = LocationManager()
var userLocation: String {
let latitude = "\(locationManager.lastLocation?.coordinate.latitude ?? 0)"
let longitude = "\(locationManager.lastLocation?.coordinate.longitude ?? 0)"
return "\(latitude),\(longitude)"
}
@ObservedObject var api = randomAPI()
var body: some View {
SomeView()
.onAppear {
api.callAPI(location: userLocation)
}
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/368984.html
