I am learning Swift to develop macOS applications and I ran into a problem. I am trying to get certain data from a JSON from the internet. I have managed to get such data and put it in simple text labels in the view but when I run Xcode and get the values, if the values from the JSON get updated, I can't see it reflected in my app. I know that I must perform a function to refresh the data but what I have always found is the function to refresh the data that is in a table, not a simple text label. So, basically to summarize, I get the values of the json file from url but if those values are updated, my app does not show them.
Values.swift
import Foundation
struct WelcomeElement: Codable {
let link: String?
let state: String?
let editable: Bool?
let type, name: String?
let groupNames: [String]?
let label, category: String?
let members: [JSONAny]?
let groupType: String?
}
typealias Datos = [WelcomeElement]
class UserItems {
func loadData(completion: @escaping (Datos) - Void) {
let url = URL(string: "http://192.168.0.15:8080/json")!
URLSession.shared.dataTask(with: url) { data, _, error in
if let error = error { print(error); return }
do {
let items = try JSONDecoder().decode([WelcomeElement].self, from: data!)
completion(items)
} catch {
print(error)
}
}.resume()
}
}
ViewController.swift
import Cocoa
class ViewController: NSViewController, NSTextFieldDelegate {
let userItems = UserItems()
@IBOutlet var itemSalida: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
userItems.loadData { users in
print(users)
if let position = users.firstIndex(where: { $0.name == "test2" }) {
DispatchQueue.main.async {
print(users[position].state!)
self.itemSalida.stringValue = users[position].state ?? "na"
}
}
}
}
}
A sample of the json in the url:
{
"link": "null",
"state": "NULL",
"editable": false,
"type": "String",
"name": "m",
"tags": [],
"groupNames": []
},
{
"link": "test1",
"state": "-1",
"stateDescription": {
"pattern": "%d",
"options": []
},
"editable": true,
"type": "Number",
"name": "test2",
"label": "Current",
"category": "",
"tags": [
"Point"
],
"groupNames": []
}
Any help will help me! Thanks!
2
0
1.6k