以下代码几天前还可以使用。我不知道更新了什么,也许是新的14.4?但它今天突然停止工作,出现了一个不伦不类的错误,我不知道这里出了什么问题。
FetchStockAPIApp.swift
import SwiftUI
@main
struct FetchStockAPIApp: App {
@StateObject public var stocks = TFViewModel()
var body: some Scene {
WindowGroup {
ContentView(stocks: stocks)
}
}
}
ContentView.swift
import SwiftUI
struct ContentView: View {
@ObservedObject var stocks : TFViewModel
let isSSL = false
public var url : String = "http://10.0.0.41:8111/xyz123"
public var sslurl: String = "https://domain.name:8100/xyz123"
var body: some View {
ScrollView {
ForEach(stocks.tfstocks!, id: .recid) { item in
Text("123")
}
}
.onAppear {stocks.fetchData(apiUrl: isSSL ? sslurl : url)}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(stocks: TFViewModel())
}
}
TFDataModel.swift
import SwiftUI
struct TFStock: Codable, Hashable {
var recid = UUID()
var symbol: String
var Close: Double
}
class TFViewModel: ObservableObject {
@Published var tfstocks: [TFStock]? = [TFStock]()
func fetchData(apiUrl: String) {
guard let url = URL(string: apiUrl) else {
print("URL is not valid")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) {
data, response, error in
if let data = data { // data is Optional, so
// you need to unwrap it
if let decodedResult = try?
JSONDecoder().decode(
[TFStock].self, from: data) {
// decoding is successful
DispatchQueue.main.async {
// assign the decoded articles to
// the state variable
self.tfstocks = decodedResult
}
//print(decodedResult)
return
}
}
print("Error: (error?.localizedDescription ?? "Unknown error in API Fetch")")
}.resume()
}
}
从SSL url中删除XXX,使API调用在代码中工作。如果有人能在这里帮助我,我将不胜感激。
您需要将isSSL=true设置为ON,以便使用域名,因为其他IP在我的本地网络上只是同一个API。
我建议您阅读更多关于Codable
协议及其用途的信息。您可以参考下面的链接。
https://medium.com/@pleelaprasad/codable-protocols-in-swift-76f8b088c483。
catch块在下面为您的代码打印错误。
keyNotFound(编码键(字符串值:"recid",intValue:nil(,Swift。DecodingError.Context(编码路径:[_JSONKey(字符串值:"索引0";,intValue:0(],debugDescription:";没有与键关联的值编码键(字符串值:"recid",intValue:nil(("recid"(&";,underlyingError:nil((错误:API获取中出现未知错误
我已经使用poster验证了这一点。
以下是有效的解决方案。
import SwiftUI
struct ContentViewsss: View {
@ObservedObject var stocks : TFViewModel
let isSSL = true
public var url : String = "http://10.0.0.41:8111/xyz123"
public var sslurl: String = "https://domain.name/xyz123"
var body: some View {
ScrollView {
ForEach(stocks.tfstocks!, id: .recid) { item in
Text(item.symbol)
}
}
.onAppear {stocks.fetchData(apiUrl: isSSL ? sslurl : url)}
}
}
struct TFStock: Codable, Hashable {
var recid = UUID()
var symbol: String
var Close: Double
private enum CodingKeys : String, CodingKey {
case symbol, Close
}
}
class TFViewModel: ObservableObject {
@Published var tfstocks: [TFStock]? = [TFStock]()
func fetchData(apiUrl: String) {
guard let url = URL(string: apiUrl) else {
print("URL is not valid")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) {
data, response, error in
if let data = data { // data is Optional, so
// you need to unwrap it
do{
let decodedResult = try
JSONDecoder().decode(
[TFStock].self, from: data)
// decoding is successful
DispatchQueue.main.async {
// assign the decoded articles to
// the state variable
self.tfstocks = decodedResult
}
//print(decodedResult)
return
}catch let error{
print(error)
}
}
print("Error: (error?.localizedDescription ?? "Unknown error in API Fetch")")
}.resume()
}
}