Post

Replies

Boosts

Views

Activity

'init()' is deprecated: Use init(configuration:) instead and handle errors appropriately.
Hello I'm trying to detect objects with CreateML, but it gives me this warning that I think is breaking my app: 'init()' is deprecated: Use init(configuration:) instead and handle errors appropriately. The classfier.model is a CreatML model that has some images Have any ideas on how to fix it? import UIKit import AVKit import Vision import CoreML class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate { 		 		let identifierLabel: UILabel = { 				let label = UILabel() 				label.backgroundColor = .white 				label.textAlignment = .center 				label.translatesAutoresizingMaskIntoConstraints = false 				return label 		}() 		override func viewDidLoad() { 				super.viewDidLoad() 				 				// here is where we start up the camera 				// for more details visit: https://www.letsbuildthatapp.com/course_video?id=1252 				let captureSession = AVCaptureSession() 				captureSession.sessionPreset = .photo 				 				guard let captureDevice = AVCaptureDevice.default(for: .video) else { return } 				guard let input = try? AVCaptureDeviceInput(device: captureDevice) else { return } 				captureSession.addInput(input) 				 				captureSession.startRunning() 				 				let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) 				view.layer.addSublayer(previewLayer) 				previewLayer.frame = view.frame 				 				let dataOutput = AVCaptureVideoDataOutput() 				dataOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "videoQueue")) 				captureSession.addOutput(dataOutput) 				 				 				 				setupIdentifierConfidenceLabel() 		} 		 		fileprivate func setupIdentifierConfidenceLabel() { 				view.addSubview(identifierLabel) 				identifierLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -32).isActive = true 				identifierLabel.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true 				identifierLabel.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true 				identifierLabel.heightAnchor.constraint(equalToConstant: 50).isActive = true 		} 		 		func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { //				print("Camera was able to capture a frame:", Date()) 				 				guard let pixelBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return } 				 				// !!!Important 				// make sure to go download the models at https://developer.apple.com/machine-learning/ scroll to the bottom 				guard let model = try? VNCoreMLModel(for: Classfier().model) else { return } 				let request = VNCoreMLRequest(model: model) { (finishedReq, err) in 						 						//perhaps check the err 						 //						print(finishedReq.results) 						 						guard let results = finishedReq.results as? [VNClassificationObservation] else { return } 						 						guard let firstObservation = results.first else { return } 						 						print(firstObservation.identifier, firstObservation.confidence) 						 						DispatchQueue.main.async { 								self.identifierLabel.text = "\(firstObservation.identifier) \(firstObservation.confidence * 100)" 						} 						 				} 				 				try? VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]).perform([request]) 		} } Thank you for your time
2
1
4.9k
Jan ’21
ForEach and HStack
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
8
0
1.6k
Mar ’21
Index Out of Range
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
6
0
1.1k
Mar ’21
Looping views SwiftUI
Hello Is there a view to loop different views, for example in a ForEach loop Here is what I mean: import SwiftUI struct ContentView: View { 		@State var view1 = false 		@State var view2 = false 		@State var view3 = false 		@State var view4 = false 		 		private var gridItemLayout = [GridItem(.flexible()), GridItem(.flexible())] 		 		 		var textSize: CGFloat { 				if UIDevice.current.userInterfaceIdiom == .pad { 						return 48 				} 				return 23 		} 		 		var title: CGFloat { 				if UIDevice.current.userInterfaceIdiom == .pad { 						return 60 				} 				return 34 		} 		 		var height: CGFloat { 				if UIDevice.current.userInterfaceIdiom == .pad { 						return 0.15 				} 				return 0.15 		} 		 		var weight: CGFloat { 				if UIDevice.current.userInterfaceIdiom == .pad { 						return 0.44 				} 				return 0.43 		} 		 		var body: some View { 				NavigationView{ 						GeometryReader { geometry in 								ScrollView(.vertical, showsIndicators: true) { 										LazyVGrid(columns: gridItemLayout, spacing: 18){ 												Group{ 														Text("View1") 														.foregroundColor(.black) 														.frame(width: geometry.size.width * weight, height: geometry.size.height * height) 														.background(Color.white) 														.onTapGesture { 																view1 = true 														} 														 														.sheet(isPresented: $view1) { 																View1() 														} 														 														Text("View2") 														.foregroundColor(.black) 														.frame(width: geometry.size.width * weight, height: geometry.size.height * height) 														.background(Color.white) 														.onTapGesture { 																view2 = true 														} 														 														.sheet(isPresented: $view2) { 																View2() 														} 														 														Text("View3") 														.foregroundColor(.black) 														.frame(width: geometry.size.width * weight, height: geometry.size.height * height) 														.background(Color.white) 														.onTapGesture { 																view3 = true 														} 														 														.sheet(isPresented: $view3) { 																View3() 														} 														 														Text("View4") 														.foregroundColor(.black) 														.frame(width: geometry.size.width * weight, height: geometry.size.height * height) 														.background(Color.white) 														.onTapGesture { 																view4 = true 														} 														 														.sheet(isPresented: $view4) { 																View4() 														} 														 														 												} 												 										}.padding() 										 								} 								 						} 						.navigationTitle("Title") 						 				} 		} 		 		 } Is there a way to put the 4 views in a loop instead of making four different Text Views(they are different views) Thank your for your time
4
0
4.4k
Mar ’21
Comma not working
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
10
0
848
Mar ’21
Problems with ForEach, SwiftUI
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
3
0
2.6k
Apr ’21
Errors in ForEach SwiftUI
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
3
0
3.6k
Apr ’21
Cannot use instance member 'name' within property initializer; property initializers run before 'self' is available
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
2
0
4.4k
Apr ’21
Touch and Face ID in SwiftUI
Hello Is there a way to know if the detected finger or face are wrong? I am using this function: func authenticate() { let context = LAContext() var error: NSError? if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) { let reason = "We need to unlock your data." context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { success, authenticationError in DispatchQueue.main.async { if success { self.isUnlocked = true } else { userPressedCancel = false } } } } else { } }
1
0
940
Apr ’21
.trim() Shape SwiftUI
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
7
0
2.3k
Apr ’21
Index out of range, SwiftUI
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
5
0
2.1k
Jun ’21
DecimalPad Issues SwiftUI
Hello I have two questions: I'm using a decimalpad keyboard and when I use the comma the app doesn't recognise it How do I dismiss the keyboard? I want that in every country the decimals are written with the comma ( , ) (Can you please write the solution if you know it, thank you for your time) Code: import SwiftUI struct BMIView: View {          @State private var height = ""     @State private var weight = ""     @Environment(\.presentationMode) var presentationMode     var inputAfterConvertions: Float {          let hh = Float(height) ?? 0          let ww  = Float(weight) ?? 0          var ris: Float = 0          if hh > 0 && ww > 0{          ris = (ww / (hh * hh)) * 1000             return ris         }            return 0     }          var health: String{          if inputAfterConvertions < 18.49 && inputAfterConvertions > 0 { return ""         }         else if inputAfterConvertions > 18.5 && inputAfterConvertions < 24.99{             return ""         } else if inputAfterConvertions > 25{             return ""         }                  return ""     }     @State var isWriting: Bool = false     var body: some View {         NavigationView{             Form{                 Section(header: Text("Enter your height in cm")){                     TextField("Input",text: $height)                         .keyboardType(.decimalPad)                 }                 Section(header: Text("Enter your Weight in kg")){                     TextField("Input",text: $weight)                         .keyboardType(.decimalPad)                 }                 Section(header: Text("Check result")){                     Text("\(inputAfterConvertions, specifier: "%.2f")")                 }             }             .navigationBarTitle("BMI")             .navigationBarItems(trailing:                                     Button(action: {                                         presentationMode.wrappedValue.dismiss()                                     }) {                                         Image(systemName: "xmark").font(.title).foregroundColor(.blue)                                     }             )         }     } } Thank you very much for your time
3
0
5.4k
Jun ’21