Swift: iOS 15 之前的任务 {}?

Swift: task {} before iOS 15?

我正在按照教程了解 SwiftUI,特别是如何在出现视图时调用 API。

我看到了这个:

List(results, id: \.trackId) { item in
    ListRow(item)
}
.task {
    // perform API here
}

但是由于我的应用面向 iOS14,我收到此错误:

'task(priority:_:)' is only available in iOS 15.0 or newer

那我还能做什么呢?感谢您的帮助

import SwiftUI

struct ContentView: View {
    
    @State var results = [TaskEntry]()
  
    var body: some View {
        List(results, id: \.id) { item in
            VStack(alignment: .leading) {
                Text(item.title)
            }
// this one onAppear you can use it
        }.onAppear(perform: loadData)
    }
    
  
    func loadData() {
        guard let url = URL(string: "https://jsonplaceholder.typicode.com/todos") else {
            print("Your API end point is Invalid")
            return
        }
        let request = URLRequest(url: url)

        URLSession.shared.dataTask(with: request) { data, response, error in
            if let data = data {
                if let response = try? JSONDecoder().decode([TaskEntry].self, from: data) {
                    DispatchQueue.main.async {
                        self.results = response
                    }
                    return
                }
            }
        }.resume()
    }
    
}

async await 适用于 iOS 13+。

https://developer.apple.com/documentation/swift/task

如果您需要使用 async 调用,请将调用包装在 Task

.onAppear(){
    Task{
        //Your async code here
        // await yourFuncHere()
    }
}     

.onAppear 有点不可靠,所以我可能会选择 initObservableObject 作为替代。

您可以编写适用于 iOS 13、iOS 14 并使用苹果版本适用于 iOS 15 的 task { } 版本:

extension View {
    @available(iOS, deprecated: 15.0, message: "This extension is no longer necessary. Use API built into SDK")
    func task(priority: TaskPriority = .userInitiated, _ action: @escaping @Sendable () async -> Void) -> some View {
        self.onAppear {
            Task(priority: priority) {
                await action()
            }
        }
    }
}