everyone.我有一个问题。我想不通。我想从我的服务器获取数据(JSON数组(,它无法正常工作。它不会显示任何内容。HTTP 标头:文本/纯文本。我以这个来源为例:https://medium.com/@rbreve/displaying-a-list-with-swiftui-from-a-remote-json-file-6b4e4280a076 .这是我的代码和数据:
import Foundation
import SwiftUI
import Combine
struct Medewerker: Codable, Identifiable, Hashable {
public var id : Int
public var naam: String
public var voornaam: String
}
struct SwiftUIView2: View {
@ObservedObject var fetcher = MedewerkerFetcher()
var body: some View {
VStack {
List(fetcher.medewerker) { medewerker in
VStack (alignment: .leading) {
Text(medewerker.naam)
Text(medewerker.voornaam)
.font(.system(size: 11))
.foregroundColor(Color.gray)
}
}
}
}
}
struct SwiftUIView2_Previews: PreviewProvider {
static var previews: some View {
SwiftUIView2()
}
}
public class MedewerkerFetcher: ObservableObject {
@Published var medewerker = [Medewerker]()
init(){
load()
}
func load() {
let url = URL(string: "http://anwin.be/src/public/medewerker")!
var request = URLRequest(url: url)
request.addValue("text/plain", forHTTPHeaderField: "Accept")
URLSession.shared.dataTask(with: request) {(data,response,error) in
if let mimeType = response?.mimeType, mimeType == "text/plain"{
do {
if let d = data {
let decodedLists = try JSONDecoder().decode([Medewerker].self, from: d)
DispatchQueue.main.async {
self.medewerker = decodedLists
}
}else {
print("No Data")
}
} catch {
print ("Error")
}
}
}.resume()
}
}
数据。来自服务器的 Json:
[
{
"id": 1,
"naam": "Fanoberov",
"voornaam": "Andre"
},
{
"id": 2,
"naam": "Kunitski",
"voornaam": "Dzmitry"
},
{
"id": 7,
"naam": "Karim",
"voornaam": "Nassar"
}
]
你能帮我吗? 谢谢。
错误是:
{Error Domain=kCFErrorDomainCFNetwork Code=-1022 "(null)"}, NSErrorFailingURLKey=http://dtcws.azurewebsites.net/ShowImg.aspx?params=dtc_376_0_True_False_22, NSLocalizedDescription=The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.})
你必须改变你的信息列表 添加这个:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>