How can I read json from url, output to app screen? SwiftUI - json

I`m new at swift and need to read json file from url. I managed to get the data and output it to the console, but how can I get it to the application screen?
import SwiftUI
struct User: Codable {
let Login: String
let Password: String
}
struct AllTEC: View {
var body: some View {
Text("asd").onAppear(perform: loadD)
}
}
extension AllTEC
{
func loadD() {
let url = URL(string: "https://symbiosys-a415a.firebaseio.com/USER.json")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard error == nil else {
print("error: \(error!)")
return
}
guard let data = data else{
print("no data")
return
}
guard let user = try? JSONDecoder().decode(User.self, from: data) else {
print("Error: Couldn't decode data ito user")
return
}
print("gotten user is \(user.Login)")
}
task.resume()
}
}
struct AllTEC_Previews: PreviewProvider {
static var previews: some View {
AllTEC()
}
}
The json structure is pretty simple.
{
"Login":"Kapitan",
"Password":"M3030"
}

Simply make a #State variable user for storing the returned User in AllTEC.
struct AllTEC: View {
#State var user: User?
var body: some View {
Text("Login: \(user?.Login ?? "")")
.onAppear(perform: loadD)
}
}
And set user right after you decode it in the network call:
print("gotten user is \(user.Login)")
DispatchQueue.main.async {
self.user = user
}

Related

SwiftUI Fetching JSON API Data from api.city.bik

I am having issues trying to get this data. I heard there is a trick. Can anyone create a simple call to view the data from this api? Would truly appreciate it. Been trying for a week. I cant for the life of me get this simple api call to work.
http://api.citybik.es/v2/networks
Model.swift
import Foundation
// MARK: - Welcome
struct Dataset: Codable {
let networks: [Network]
}
// MARK: - Network
struct Network: Codable {
let company: [String]
let href, id: String
let location: Location
let name: String
}
// MARK: - Location
struct Location: Codable {
let city, country: String
let latitude, longitude: Double
}
Contentview.swift
import SwiftUI
struct ContentView: View {
#State var results = [Network]()
func loadData() {
guard let url = URL(string: "http://api.citybik.es/v2/networks") 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([Network].self, from: data) {
DispatchQueue.main.async {
self.results = response
}
return
}
}
}.resume()
}
var body: some View {
List(results, id: \.name) { item in
VStack(alignment: .leading) {
Text("\(item.name)")
}
}.onAppear(perform: loadData)
}
}
copy the whole of the json from : "https://api.citybik.es/v2/networks"
into "https://app.quicktype.io/" and get the (correct) swift data structures from that.
Rename "Welcome" to "Response" and use that in your code.
use: "https://api.citybik.es/v2/networks" note the https.
EDIT: In your code:
struct ContentView: View {
#State var networks = [Network]()
var body: some View {
List(networks, id: \.id) { network in
VStack {
Text(network.name)
Text(network.location.city)
}
}.onAppear(perform: loadData)
}
func loadData() {
guard let url = URL(string: "https://api.citybik.es/v2/networks") 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(Response.self, from: data) {
DispatchQueue.main.async {
self.networks = response.networks
}
return
}
}
}.resume()
}
}
Once you have all the data structures,
and if you are using Swift 5.5 for ios 15 or macos 12, you can use something like this:
struct ContentView: View {
#State var networks = [Network]()
var body: some View {
List(networks, id: \.id) { network in
VStack {
Text(network.name)
Text(network.location.city)
}
}
.task {
let response: Response? = await fetchNetworks()
if let resp = response {
networks = resp.networks
}
}
}
func fetchNetworks<T: Decodable>() async -> T? {
let url = URL(string: "https://api.citybik.es/v2/networks")!
let request = URLRequest(url: url)
do {
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
// throw URLError(.badServerResponse) // todo
print(URLError(.badServerResponse))
return nil
}
let results = try JSONDecoder().decode(T.self, from: data)
return results
}
catch {
return nil
}
}
}

How to use data decoded from JSON in SwiftUI

Problem
The data is successfully decoded from Reddit’s api and put into the variable theUser inside the .onAppear {…}, but when I try to use it I keep getting nil values.
Code
struct ContentView: View {
#State var didAppear = false
#State var theUser = getNilUser()
var body: some View {
Text("User Profile")
Text(theUser.data.subreddit.display_name_prefixed ?? "No name found")
.onAppear(perform: {
theUser = getUser(withName: "markregg")
})
}
func getUser(withName username: String) -> user {
if !didAppear {
if let url = URL(string: "https://www.reddit.com/user/\(username)/about.json") {
do {
let data = try Data(contentsOf: url)
do {
let decodedUser = try JSONDecoder().decode(user.self, from: data)
return decodedUser
} catch {
print(error)
}
} catch {
print(error)
}
}
didAppear = true
}
return getNilUser()
}
}
Edit: I’m very new to this so if I made a stupid mistake I’m sorry
You can't get JSON data like that. You have to execute a HTTP request using the URLSession class in order to get the data and parse it.
let username = "markregg"
let url = URL(string: "https://www.reddit.com/user/\(username)/about.json")!
URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print(error)
} else if let data = data {
do {
let decodedUser = try JSONDecoder().decode(User.self, from: data)
} catch {
print(error)
}
} else {
print("Request failed")
}
}.resume()
Another thing to note is that URLSession methods are asynchronous. In simple terms it means they take some time to execute and return the result. So you can't use a simple return statement like return decodedUser to get the result right away. Look into how to use URLSession more.

Decoding Exchange Rate JSON in SwiftUI

I am trying to decode https://api.exchangeratesapi.io/latest, provided by Exchange Rates API. I'm applying several tutorials I found online, but when I apply my own details, I get an error. My code looks as following:
struct Response: Codable {
var results: [Result]
}
struct Result: Codable {
let base: String
let date: String
let rates: [String:Double]
}
The function to retrieve the data:
func loadData() {
guard let url = URL(string: "https://api.exchangeratesapi.io/latest") else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
// we have good data – go back to the main thread
DispatchQueue.main.async {
// update our UI
self.results = decodedResponse.results
}
// everything is good, so we can exit
return
}
}
// if we're still here it means there was a problem
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}.resume()
}
And my view:
import SwiftUI
struct ExchangeRateTest: View {
#State private var results = [Result]()
var body: some View {
List(results, id: \.base) { item in
VStack(alignment: .leading) {
Text(item.base)
}
}.onAppear(perform: loadData)
}
}
The error I get is: Fetch Failed: Unknown Error, suggesting that the app is not able to read the online data. What can cause this?
It has nothing to do with my network connection; if I apply another JSON this approach works fine.
Any help would greatly be appreciated.
you can read like this:
struct RateResult: Codable {
let rates: [String: Double]
let base, date: String
}
struct ContentView: View {
#State private var results = RateResult(rates: [:], base: "", date: "")
func loadData() {
guard let url = URL(string: "https://api.exchangeratesapi.io/latest") else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
if let decodedResponse = try? JSONDecoder().decode(RateResult.self, from: data) {
// we have good data – go back to the main thread
DispatchQueue.main.async {
// update our UI
self.results = decodedResponse
}
// everything is good, so we can exit
return
}
}
// if we're still here it means there was a problem
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}.resume()
}

Data immediately deallocated

I am currently working on a Headline UI Element for my app and I am having an issue with my data being immediately deallocated. I have been trying to get the console to print any data it is receiving, but I am not even seen that in the console. What I am trying to achieve is for the app to connect to its targeted "CDN" and then pull data for the headlines. Using PHP I am preforming a SQL Query to generate an array that the app will then feed off of. When running said scrip the following array is generated.
{"id":"1","title":"Meet ergoWare","header_image":"https://gba.ergoware.io/cache/content/topstory/ergo_news_01.svg","summary":"GBA's New Ergonomic Portal!"}
Stunning array yeah, so the next part is it will then be read and compiled in the app to create headline cards, but the issue is I cannot get the data to to load. I know there is something I am missing, but without the compiler pointing me in the direction I need, I'm fumbling around with it. So here is the Swift code.
import SwiftUI
struct Response: Codable {
var results: [Article]
}
struct Article: Codable, Identifiable {
var id: Int
var title: String
var header_image: String
var summary: String
}
struct HeadlineUI: View {
#State var results = [Article]()
var CDNLink: String
var body: some View {
ScrollView(.horizontal) {
HStack(spacing: 20) {
ForEach(results) { result in
CardView(image: result.header_image, summary: result.summary, heading: result.title)
}
.onAppear(perform: { self.loadData() })
}
}
}
func loadData() {
guard let url = URL(string: CDNLink) else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
DispatchQueue.main.async {
self.results = decodedResponse.results
print(self.results)
}
return
}
}
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}.resume()
}
}
struct HeadlineUI_Previews: PreviewProvider {
static var previews: some View {
HeadlineUI(CDNLink: "https://gba.ergoware.io/cdn?funct=fetchNews")
}
}
So what should happen is that it connects to the "CDN" and reads the array. That information then is plugged in and for each index of the results, defined by the id, a card should display with the top story image, article header and a short summary. I am starting to get a little more comfortable with Swift, but little hiccups like this keeps breaking my confidence down haha. Thanks for any teachable moments you can provide.
I found it, follow these steps:
According to your class Response, your service should return this JSON:
{
"results" : [{
"id":1,
"title":"Meet ergoWare",
"header_image":"https://gba.ergoware.io/cache/content/topstory/ergo_news_01.svg",
"summary":"GBA's New Ergonomic Portal!"
}]
}
Give it a try using this url
You should place .onAppear in your HStack not in your ForEach. Here is a the full example:
struct Response: Codable {
var results: [Article]
}
struct Article: Codable, Identifiable {
var id: Int
var title: String
var header_image: String
var summary: String
}
struct HeadlineUI: View {
#State var results = [Article]()
var CDNLink: String
var body: some View {
ScrollView(.horizontal) {
HStack(spacing: 20) {
Text("Response:")
ForEach(results) { result in
Text(result.title)
}
}.onAppear(perform: { self.loadData() })
}
}
func loadData() {
guard let url = URL(string: CDNLink) else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if error != nil {
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
return
} else {
do {
let decodedResponse = try JSONDecoder().decode(Response.self, from: data!)
print(decodedResponse)
self.results = decodedResponse.results
} catch let err {
print("Error parsing: \(err)")
}
}
}.resume()
}
}

SwiftUI: Display JSON Data with Text() instead of List

I have got a problem with displaying JSON data on a SwiftUI View.
I tried several tutorials and read articles which are related to my problem, but nothing seems appropriate enough.
For example everyone displays JSON data from an API with a fancy list or pictures, but I only want to know how you can simply display one word on a view (without List{}).
I chose the PokeAPI to figure out how to display "Hi Charmander" with the Text() instruction.
Example of a list (and without ObservableObject and #Published)
I want to get rid of the List and use sth. Text(resultsVar[0].name).onAppear(perform: loadData) like instead
import SwiftUI
struct pokeRequest:Codable {
var results: [Result]
}
struct Result:Codable {
var name:String
}
struct ViewOne: View {
#State var resultsVar = [Result]()
var body: some View {
VStack{
//unfortunately this does not work:
//Text(resultsVar[0].name).onAppear(perform: loadData)
List(resultsVar, id: \.name) { item in
VStack(alignment: .leading) {
Text("Hi \(item.name)")
}
}
.onAppear(perform: loadData)
}
}
func loadData(){
guard let url = URL(string: "https://pokeapi.co/api/v2/pokemon?offset=3&limit=3") else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
if let decodedResponse = try? JSONDecoder().decode(pokeRequest.self, from: data) {
DispatchQueue.main.async {
self.resultsVar = decodedResponse.results
}
return
}
}
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}.resume()
}
}
struct ViewOne_Previews: PreviewProvider {
static var previews: some View {
ViewOne()
}
}
Second try with a different approach (without .onAppear())
In this approach I tried with class: Observable Object and #Published but I also didn't come to my wished UI-output.
import SwiftUI
struct pokeRequest2:Codable {
var results2: [pokeEach2]
}
struct pokeEach2:Codable {
var name2:String
}
class Webservice:ObservableObject {
#Published var pokeInfo: [pokeRequest2] = [pokeRequest2]()
func decodepokemon() {
let session = URLSession.shared
let url = URL(string: "https://pokeapi.co/api/v2/pokemon?offset=3&limit=3")!
let task = session.dataTask(with: url) { data, response, error in
if error != nil || data == nil {
print("Client error!")
return
}
guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
print("Server error!")
return
}
guard let mime = response.mimeType, mime == "application/json" else {
print("Wrong MIME type!")
return
}
do {
let response = try JSONDecoder().decode(pokeRequest2.self, from: data!)
print(self.pokeInfo[0].results2[0].name2)
DispatchQueue.main.async {
self.pokeInfo = [response]
}
} catch {
print("JSON error: \(error.localizedDescription)")
}
}.resume()
}
init() {
decodepokemon()
}
}
struct ViewTwo: View {
#ObservedObject var webservice: Webservice = Webservice()
var body: some View {
Text("please help")
//Does also not work: Text(self.webservice.pokeInfo2[0].results2[0].name2)//.onAppear()
//Since a few minutes somehow the debug area prints "JSON error: The data couldn’t be read because it is missing." instead of "charmander"
}
}
struct ViewTwo_Previews: PreviewProvider {
static var previews: some View {
ViewTwo()
}
}
I tried several tutorials and read articles which are related to my problem, but nothing seems appropriate enough.
I would highly appreciate any help :-)
Thanks in advance!
I may be misunderstanding the question but in SwiftUI text can be displayed as follows:
Text("Hi" + item.name)
But as I say I'm not sure if that's the question.
As you will dynamically change the list items, you have to use .id() modifier. And in order to use .id(), the result must conforms to Hashable. The following code can help you solve the problem.
struct Result:Codable, Hashable {
var name:String
}
struct ViewOne: View {
#State var resultsVar = [Result]() // [Result(name: "firsy"),Result(name: "second"), ]//[Result]()
var body: some View {
VStack{
Spacer()
//unfortunately this does not work:
//Text(resultsVar[0].name).onAppear(perform: loadData)
List(resultsVar, id: \.name) { item in
VStack(alignment: .leading) {
Text("Hi \(item.name)")
}
}.id(resultsVar)
}.onAppear(perform: loadData)
I am by no means an expert (started using Swift less than three days ago) but I think I might have what you are looking for. This enables you to call a simple REST API that contains only a simple dictionary (in my case the dictionary contains "Differential": 5.22) and then display that number as text when a button is pressed. Hope the following is helpful!
struct DifferentialData: Decodable {
var Differential: Double
}
struct ContentView: View {
#State var data = DifferentialData(Differential: 0.00)
func getData() {
guard let url = URL(string: "Enter your URL here")
else { return } //Invalid URL
URLSession.shared.dataTask(with: url) { data, response, error in
let differentials = try! JSONDecoder().decode(DifferentialData.self, from: data!)
print(differentials)
DispatchQueue.main.async {
self.data = differentials
}
}
.resume()
}
var body: some View {
VStack{
Text("\(data.Differential)")
Button("Refresh data") {self.getData()}
}
}
}