Hello
I'm trying to fetch some data from a JSON Api, but when I access the properties of my struct it tells me Value of Type "Name Of The Struct" has no member "name of the property"
Any idea on how to fix it
Code:
import SwiftUI
import Combine
struct ContentView: View {
		
		@ObservedObject var networkController = NetworkControllerItalia()
		var gridItemLayout = [GridItem(.flexible()), GridItem(.flexible())]
		
		var body: some View {
				NavigationView{
						ScrollView{
								ForEach(networkController.users, id: \.self){ user in
										GroupBox(label: Text(user.round ?? ""), content: {
												VStack{
														Text(user.team1 ?? "")
												}
										}).padding()
						}
						.navigationTitle("Serie A")
				}
		 }
	 }
}
class NetworkControllerItalia: ObservableObject {
		private var can: AnyCancellable?
		
		let url = URL(string: "https://raw.githubusercontent.com/openfootball/football.json/master/2020-21/it.1.json")!
		//let url = URL(string: "google.com")!
		@Published var users = [UserItalia(matches: [])]
		
		init() {
				self.can = URLSession.shared.dataTaskPublisher(for: url)
						.map { $0.data }
						.decode(type: [UserItalia].self, decoder: JSONDecoder())
						//.replaceError(with: [])
						.eraseToAnyPublisher()
						.receive(on: DispatchQueue.main)
						.sink(receiveCompletion: {completion in
								print(completion)
						}, receiveValue: { users in
								self.users	= users
						})
		}
		
}
struct UserItalia: Decodable, Hashable {
		var matches: [Matches]?
}
struct Matches: Decodable, Hashable {
		var round: String?
		var date: String?
		var team1: String?
		var team2: String?
}
Thank You
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Hello
Does anyone know how to use real time image recognition in SwiftUI with a Create ML model.
Thank you
Hello
Is there any way to put the 2 Texts in an HStack without putting the 2 ForEachs together?
Code:
ForEach(model.data, id: \.objectID){ obj in
Text(model.getValue(obj: obj))
}.onDelete(perform: model.deleteData)
ForEach(date.data, id: \.objectID){ obj1 in
Text("\(date.getValue(obj: obj1), formatter: dateFormatter)")
}.onDelete(perform: date.deleteData)
Thank you
Hello
How do I solve the Index out of range at line 81
I tried many ways, but none of them worked
//
// ContentView.swift
// Fede
//
// Created by Jad Taljabini on 14/03/21.
//
import SwiftUI
struct ContentView: View {
@State private var media: String = ""
@State private var voto: String = ""
@State private var voti: [Float] = []
@State private var nVoti: Int = 0
@State private var test: String = ""
@State private var voti2: [Float] = []
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
NavigationView {
Form {
Section{
TextField("A che media vuoi arrivare", text: $media)
}
Section{
TextField("Quanti voti prenderai", text: $test)
}
Section{
HStack {
TextField("Tuoi voti", text: $voto)
Spacer()
Button(action: {
voti.append(Float(voto) ?? 0)
voto = ""
nVoti = nVoti + 1
}, label: {
Text("Add")
})
}
}
Section{
ForEach(voti, id: \.self){ item in
Text("\(item, specifier: "%.1f")")
}.onDelete(perform: removeRows)
}
Section(header: Text("Voti che devi prendere")){
ForEach(voti2, id: \.self){ item2 in
Text("\(item2)")
}
}
}.onReceive(timer) { input in
voti2 = tutto()
}
.navigationTitle("Media")
}
}
func tutto() - [Float] {
let testInt = Int(test) ?? 0
let mediaFloat = Float(media) ?? 0
var mediaEffettiva = mediaEffFunzione(dim: nVoti)
if mediaEffettiva mediaFloat {
for i in 0..testInt - 2 {
voti2[i] = Float(Int(mediaEffettiva + 1))
}
let mediaEffettivaInt = Int(mediaEffettiva)
let mediaFloatInt = Int(mediaFloat)
var con: Int = 0
while(mediaEffettivaInt mediaFloatInt){
for j in nVoti..nVoti + testInt - 2{
voti[j] = voti2[j - nVoti];
}
mediaEffettiva = mediaEffFunzione(dim: nVoti + testInt)
if(mediaEffettiva mediaFloat){
voti2[con] += 0.5
}
con = con + 1
if con = testInt {
con = 0
}
}
}
return voti2
}
func removeRows(at offsets: IndexSet) {
voti.remove(atOffsets: offsets)
}
func mediaEffFunzione(dim: Int) - Float {
var somma: Float = 0
for i in voti{
somma = somma + i
}
return somma / Float(dim)
}
}
Thank you very much
Hello, Is there a way to use "switch statement" inside of a NavigationLink Destination?
Example:
NavigationLink(destination:
switch i {
case 0: MatematicaView()
case 1: ArteView()
default: EmptyView()
}){
Text("Hello")
}
(The views are different, that's why I don't put them in one struct)
Thank you
Hello
Is there a way to append a number to a Double, like this:
var num: Double = 1
var num2 = num.append(1)
//num2 should be 11
Thank you
Hello
Do you know why the comma in this calculator app isn't working:
import SwiftUI
import Combine
enum Nums: String{
case uno = "1"
case due = "2"
case tre = "3"
case quattro = "4"
case cinque = "5"
case sei = "6"
case sette = "7"
case otto = "8"
case nove = "9"
case zero = "0"
case moltiplicazione = "X"
case divisione = "/"
case somma = "+"
case meno = "-"
case uguale = "="
case AC = "AC"
case piùMeno = "±"
case percentuale = "%"
case virgola = "."
case niente = ""
}
struct ContentView: View {
var numeri: [[Nums]] = [
[Nums.AC, Nums.piùMeno, Nums.percentuale, Nums.divisione],
[Nums.sette, Nums.otto, Nums.nove, Nums.moltiplicazione],
[Nums.quattro, Nums.cinque, Nums.sei, Nums.meno],
[Nums.uno, Nums.due, Nums.tre, Nums.somma],
[Nums.zero, Nums.niente, Nums.virgola, Nums.uguale]
]
private var gridItemLayout = [GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible())]
@State var previousVar: Double = 0
let timer = Timer.publish(every: 0.001, on: .main, in: .common).autoconnect()
@State var con: Int = 0
@State var final: Double = 0
@State var operat = Nums(rawValue: "")
@State var digits: String = "0"
var res: Double {
get {
//digits.hasSuffix(".") ? Double(digits.dropLast()) ?? 0.0 : Double(digits) ?? 0.0
digits.hasSuffix(".") ? Double(digits) ?? 0.0 : Double(digits) ?? 0.0
}
nonmutating set {
digits = String(format: "%.10g", newValue) //- May need better formatting
}
}
var body: some View {
VStack{
Spacer()
HStack{
Spacer()
Text("\(digits)")
.font(.system(size: 50))
.bold()
.padding()
}
Spacer()
LazyVGrid(columns: gridItemLayout, content: {
ForEach(0..5){ i in
ForEach(0..4){ j in
RoundedRectangle(cornerRadius: 35.0)
.foregroundColor(.orange)
.frame(width: 80, height: 80, alignment: .center)
.overlay(
Text("\(numeri[i][j].rawValue)")
.font(.largeTitle)
.foregroundColor(.black)
).onTapGesture {
switch numeri[i][j] {
case Nums.AC:
operat = Nums.AC;
res = 0
case Nums.uguale:
operat = Nums.uguale;
res = final
case Nums.somma:
operat = Nums.somma;
previousVar = res;
res = 0;
con = 0
case Nums.meno:
operat = Nums.meno;
previousVar = res;
res = 0
con = 0
case Nums.divisione:
operat = Nums.divisione;
previousVar = res;
res = 0;
con = 0
case Nums.moltiplicazione:
operat = Nums.moltiplicazione;
previousVar = res;
res = 0;
con = 0
case Nums.percentuale:
operat = Nums.percentuale;
res = res / 100
case Nums.piùMeno:
operat = Nums.piùMeno;
if digits.hasPrefix("-") {
digits = String(digits.dropFirst())
} else {
digits = "-" + digits
}
con = 0
case Nums.virgola:
operat = Nums.virgola;
if !digits.contains(".") {
digits += "."
}
default:
if digits == "0" {
digits = numeri[i][j].rawValue
} else {
digits += numeri[i][j].rawValue
}
con += 1
}
}
}
}
}).onReceive(timer) { _ in
if con != 0 {
if operat == Nums.divisione{
final = previousVar / res
} else if operat == Nums.meno{
final = previousVar - res
} else if operat == Nums.moltiplicazione{
final = previousVar * res
} else if operat == Nums.somma{
final = previousVar + res
}
}
}
}.padding(2)
}
}
Maybe at line 51 and 52 or 121
(If you can explain my mistakes all around the code I would be grateful)
Thank you
Hello
I am getting a lot of errors in ForEach and I don't know why at all.
Here is the code:
The error is at line 12
import SwiftUI
import Combine
struct ContentView: View {
@EnvironmentObject var networkController: NetworkControllerItalia
var body: some View {
Form{
TextField("Input city name", text: $networkController.cityName)
Section {
ForEach(networkController.users.weather, id: \.self){ user in
}
}
}
}
}
class NetworkControllerItalia: ObservableObject {
private var can: AnyCancellable?
@Published var cityName: String = ""
@Published var users = [UserItalia(weather: Weather())]
init(cityName: String) {
self.cityName = cityName
let url = URL(string: "http://api.openweathermap.org/data/2.5/weather?q=\(cityName)&appid=")!
self.can = URLSession.shared.dataTaskPublisher(for: url)
.map { $0.data }
.decode(type: [UserItalia].self, decoder: JSONDecoder())
.eraseToAnyPublisher()
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: {completion in
print(completion)
}, receiveValue: { users in
self.users = users
})
}
}
struct UserItalia: Decodable, Hashable{
var weather: Weather
}
struct Weather: Decodable, Hashable {
var main: String?
}
Thank you
Hello
I get errors in ForEach that I don't know how to solve:
Generic struct 'ForEach' requires that 'Main' conform to 'RandomAccessCollection'
Unable to infer type of a closure parameter 'user' in the current context
Error at line 30 - 31
Code:
//
// ContentView.swift
// ARWeather
//
// Created by Jad Taljabini on 08/04/21.
//
import SwiftUI
import Combine
struct ContentView: View {
@EnvironmentObject var networkController: NetworkControllerItalia
var body: some View {
NavigationView {
Form{
TextField("Input city name", text: $networkController.cityName, onEditingChanged: { te_xt in
networkController.url = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=\(networkController.cityName)&appid=") ?? URL(string: "https://www.apple.com")!
networkController.fun()
}, onCommit: {
withAnimation{
networkController.url = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=\(networkController.cityName)&appid=") ?? URL(string: "https://www.apple.com")!
networkController.fun()
}
})
Section {
ForEach(networkController.users.weather ?? [], id: \.self){ user in
Text(user.main ?? "")
}
ForEach(networkController.users.main ?? Main(temp: 0), id: \.self){ user in
Text("\(user.temp)")
}
}
}
}
}
}
class NetworkControllerItalia: ObservableObject {
private var can: AnyCancellable?
@Published var cityName: String = ""
@Published var users = UserItalia(weather: [])
var url = URL(string: "https://www.apple.com")!
func fun(){
self.can = URLSession.shared.dataTaskPublisher(for: url)
.map { $0.data }
.decode(type: UserItalia.self, decoder: JSONDecoder())
.eraseToAnyPublisher()
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: {completion in
print(completion)
}, receiveValue: { users in
self.users = users
})
}//Funzione che riempe users di dati da internet
}
struct UserItalia: Decodable, Hashable{
var weather: [Weather]?
var main: Main?
}
struct Weather: Decodable, Hashable {
var main: String?
}
struct Main: Decodable, Hashable {
var temp: Float
}
The JSON API is like this:
{
"coord": {
"lon": -0.1257,
"lat": 51.5085
},
"weather": [
{
"id": 801,
"main": "Clouds",
"description": "few clouds",
"icon": "02d"
}
],
"base": "stations",
"main": {
"temp": 285.45,
"feels_like": 283.96,
"temp_min": 284.82,
"temp_max": 285.93,
"pressure": 1021,
"humidity": 47
},
"visibility": 10000,
"wind": {
"speed": 5.66,
"deg": 220
},
"clouds": {
"all": 20
},
"dt": 1617888145,
"sys": {
"type": 1,
"id": 1414,
"country": "GB",
"sunrise": 1617859180,
"sunset": 1617907473
},
"timezone": 3600,
"id": 2643743,
"name": "London",
"cod": 200
}
Thank you
Hello
Why does it give me an error when I pass 'name' at line 3?
struct OtherView: View {
@State private var name: String = ""
@ObservedObject var use = Use(name: name)
var body: some View{
VStack{
}
}
}
class Use: ObservableObject {
@Published var name: String
init(name: String) {
self.name = name
}
}
Thank you
Hello
I have a Raindrop shape:
struct Raindrop: Shape {
func path(in rect: CGRect) - Path {
Path { path in
path.move(to: CGPoint(x: rect.size.width / 2, y: 0))
path.addQuadCurve(to: CGPoint(x: rect.size.width / 2, y: rect.size.height), control: CGPoint(x: rect.size.width, y: rect.size.height))
path.addQuadCurve(to: CGPoint(x: rect.size.width / 2, y: 0), control: CGPoint(x: 0, y: rect.size.height))
}
}
}
When I trim it in the ContentView, it trims from right to left, is there a way to trim it from top to bottom?
Raindrop()
.trim(from: 0.9, to: 1)
.scaledToFit()
Thank you
Hello
import SwiftUI
enum When: String {
case Today
case Week
case Month
case Year
}
struct ChartView: View {
var when: When
@EnvironmentObject var millilitriInseritiModel: MillilitriInseritiModel
var valoriAsseX: [String]{
if when == When.Week{
return ["M", "T", "W", "T", "F", "S", "S"]
} else if when == When.Month{
return ["7", "14", "21", "28"]
} else if when == When.Year{
return ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]
}
return []
}
var valoriAsseY: [Double]{
return []
}
var dates: [Date] = [Date(), Date().addingTimeInterval(86400), Date().addingTimeInterval(86400 * 2)]
@State var valori: [Double] = [1000, 2000, 3000, 1000, 2000, 1000, 2000, 3000, 1000, 2000, 3000]
var altezzaRettangolo: [Double]?{
var altezze: [Double] = []
for i in 0..<valori.count{
altezze.append(valori[i])
}
return altezze
}
@State var animation: Bool = false
var body: some View{
HStack(alignment: .bottom, spacing: 8, content: {
ForEach(valoriAsseX.indices){ i in
VStack{
RoundedRectangle(cornerRadius: 3)
.fill(LinearGradient(gradient: Gradient(colors: [Color.red, Color.blue]), startPoint: .top, endPoint: .bottom))
.frame(width: 40, height: animation ? CGFloat(altezzaRettangolo?[i] ?? 0) / 7 : 0)
.animation(.easeInOut)
Text(valoriAsseX[i])
.fontWeight(.semibold)
.multilineTextAlignment(.leading)
.onTapGesture {
withAnimation{
valori[i] += 100
}
}
}
}
})
.padding()
.onAppear {
animation = true
}
.onDisappear {
animation = false
}
}
}
struct ChartView_Previews: PreviewProvider {
static var previews: some View {
ChartView(when: When.Year)
}
}
As you might notice, in the previews I set when to When.Year, that is crashing the app because the array valoriAsseX is bigger than the array altezzaRettangolo, so when I iterate it in the ForEach loop it crashes, I can't find any way to solve this, I tried an if let but it is crashing anyway, any ideas?
Thank you
Hello
I implemented the filter function in my ForEach loop, and it works just with the valori property but not with the date property , is there a way to let it filter also the date?
I tried to remove the dateFormatter but it didn't work.
Here is the code
import SwiftUI
let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
return formatter
}()
struct Test4: View {
@State private var text: String = ""
var body: some View {
NavigationView{
if !lifetimes.isEmpty{
List{
Section(header: Text("")){
TextField("Search", text: $text)
}
Section(header: Text("")){
ForEach(lifetimes.filter { text.isEmpty || "\($0)".contains(text) }, id: \.id){ lifetimeInputs in
HStack{
Text("\(lifetimeInputs.valori, specifier: "%.0f")")
Spacer()
Text("\(dateFormatter.string(from: lifetimeInputs.date))")
}
}
}
}
.listStyle(InsetGroupedListStyle())
.navigationTitle("All History")
} else{
VStack{
Text("No Data")
.font(.largeTitle)
.fontWeight(.semibold)
.foregroundColor(.secondary)
}
.padding(.bottom)
.navigationTitle("All History")
}
}
}
}
struct LifetimeInputsModel: Identifiable {
var id = UUID()
var valori: Double
var date: Date
}
var lifetimes: [LifetimeInputsModel] = [
LifetimeInputsModel(valori: 300, date: Date()),
LifetimeInputsModel(valori: 200, date: Date() + 86400)
]
Thank you
Hello
I am developing an app with SwiftUI using CoreData and iCloudKit to sync data between platforms.
The problem is that the iCloud background update is not being triggered when staying in the application. If I make changes on both systems, the changes are being pushed, however not visible on the other device.
I need to reload the app, close the app and open again.
I already enabled iCloud capability, background notifications and push notifications.
This is my persistentContainer
var persistentContainer: NSPersistentCloudKitContainer = {
let container = NSPersistentCloudKitContainer(name: "Test7")
container.loadPersistentStores(completionHandler: {(StoreDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
container.viewContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy
return container
}()
func saveContext() {
let context = persistentContainer.viewContext
if context.hasChanges{
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
This is my model
class ItemsModel: ObservableObject {
init() {
readData()
}
@Published var dataInputs: [Item] = []
let context = persistentContainer.viewContext
func readData(){
let request: NSFetchRequest<Item> = Item.fetchRequest()
do {
let results = try context.fetch(request)
self.dataInputs = results
} catch {
print(error.localizedDescription)
}
}
func addItem(todo: String, date: Date){
let entity = NSEntityDescription.insertNewObject(forEntityName: "Item", into: context) as! Item
entity.todo = todo
entity.date = date
do {
try context.save()
self.dataInputs.append(entity)
} catch {
print(error.localizedDescription)
}
}
func deleteItems(indexSet: IndexSet){
for index in indexSet{
do {
let obj = dataInputs[index]
context.delete(obj)
try context.save()
let index = dataInputs.firstIndex(of: obj)
dataInputs.remove(at: index!)
} catch {
print(error.localizedDescription)
}
}
}
}
and this is my view
struct ContentView: View {
@EnvironmentObject var items: ItemsModel
var body: some View {
NavigationView{
List {
ForEach(items.dataInputs) { item in
Text("Item at \(item.date!)")
}
.onDelete(perform: items.deleteItems)
}
.toolbar {
Button {
items.addItem(todo: "Hello", date: Date())
} label: {
Image(systemName: "plus")
}
}
}
}
}
Thank you
Hello
Is there way to keep calling a function (efficiently) while the view is on screen, without using a timer, in SwiftUI?