如何在 SwiftUI 视图中按下按钮读取数据,从函数调用数据

问题描述 投票:0回答:1

我正在尝试在 SwiftUI 中使用 Alamofire 来学习网络请求。我正在尝试从 URL 获取数据并将其显示在我的模拟器屏幕上。我使用了一个按钮,点击该按钮,将显示获取的数据。问题是点击按钮时没有打印任何内容。

我尝试依次使用 debugPrint() 和 print(),但是无论是在模拟器屏幕上还是在控制台中都没有打印任何内容。我如何实现同样的目标,这是我尝试过的 -->

import SwiftUI
import Alamofire

struct ContentView: View {
    
    @State var tapped : Bool = false
    
    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundStyle(.tint)
            Text("Hello, world!")
            Button(action: read, label: {
                Text("Let's Begin!")
            })
            .padding()
        }
        
    }
}

func read() {
    print ("%%%%%%%%%%%%%%%")
    AF.request("https://httpbin.org/get").response { response in
            debugPrint("Response : \(response)")
    }
}

#Preview {
    ContentView()
}
ios swift xcode swiftui alamofire
1个回答
0
投票

通常你会把它转到一个任务上,像这样:

struct ContentView: View {
    
    @State var isReading : Bool = false
    @State var result = ""

    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundStyle(.tint)
            Text("Hello, world!")
            Button(action: {
                isReading.toggle()
            }, label: {
                Text(isReading ? "Cancel" : "Let's Begin!")
            })
            .padding()
            .task(id: isReading) {
                if !isReading { return }
                result = await read()
                isReading = false
            }
        }
        
    }
}

func read() async -> String {
    print ("%%%%%%%%%%%%%%%")
    let response = await AF.request("https://httpbin.org/get") // must use async/await version of Almofire, can't use closure based async in SwiftUI View struct.
    return // processed response
}
© www.soinside.com 2019 - 2024. All rights reserved.