Posts

Post not yet marked as solved
1 Replies
178 Views
Is there any app out there that lets you browse through a CoreData database? When I first started to learn Swift, an app called Liya seemed to work. But alas, no longer. it would just make it easier if there was anything out there that let you browse the data directly. Thanks
Posted
by SergioDCQ.
Last updated
.
Post not yet marked as solved
0 Replies
161 Views
Would like to be able to bring up the iOS keyboard in a SwiftUI view without having to use a TextField? The goal would be to capture each keyup, or keydown, using .onKeyPress While I thought I could create a TextField not visible to the user, was hoping there was a cleaner way.
Posted
by SergioDCQ.
Last updated
.
Post not yet marked as solved
0 Replies
177 Views
I am trying to watch an @EnvironmentObject in the Xcode debugger and it comes up as an Invalid Expression in the View pane. If I want to view it, I need to declare it as a local variable and then assign it the value of the passed in @EnvironmentObject. While not impossible, it's a lot of work. Or maybe I am doing something incorrectly and this is a symptom of that? Would like to resolve this. encl: Example code & Screenshot, where choice is the passed/unviewable EnviornmentObject and ch is the local variable I use to view it in the debugger Project "TestingApp" File: TestingApp import SwiftUI @main struct TestingApp: App { @StateObject private var choice = Choices() var body: some Scene { WindowGroup { ContentView() .environmentObject(choice) } } } File: Choices import Foundation @MainActor class Choices: ObservableObject { @Published var aChoice = 1 @Published var bChoice = 2 } File: ContentView import SwiftUI struct ContentView: View { @EnvironmentObject private var choice: Choices var body: some View { VStack { let ch = choice Text("\(choice.aChoice)") .font(.largeTitle) .padding(.bottom) Text("2") .font(.largeTitle) } .padding() } } #Preview { ContentView() }
Posted
by SergioDCQ.
Last updated
.
Post not yet marked as solved
0 Replies
153 Views
Someone showed me the code below, when I was trying to figure out how to detect which views were being intercepted by one continuous DragGesture. It works, but I would like to find a tutorial whre I can learn what's going on here. From what I can tell, the background modifier is a closure, that calls a function which has a GeometryReader which returns a view. I've Googled .background as a closure in swiftui and still can't find any form of tutorial that discuss what is going on here. Not looking for the answers, looking to learn. Thank you struct ContentView: View { @State private var dragLocation = CGPoint.zero @State private var dragInfo = " " private func dragDetector(for name: String) -> some View { GeometryReader { proxy in let frame = proxy.frame(in: .global) let isDragLocationInsideFrame = frame.contains(dragLocation) let isDragLocationInsideCircle = isDragLocationInsideFrame && Circle().path(in: frame).contains(dragLocation) Color.clear .onChange(of: isDragLocationInsideCircle) { oldVal, newVal in if dragLocation != .zero { dragInfo = "\(newVal ? "entering" : "leaving") \(name)..." } } } } var body: some View { ZStack { Color(white: 0.2) VStack(spacing: 50) { Text(dragInfo) .foregroundStyle(.white) HStack { Circle() .fill(.red) .frame(width: 100, height: 100) .background { dragDetector(for: "red") } Circle() .fill(.white) .frame(width: 100, height: 100) .background { dragDetector(for: "white") } Circle() .fill(.blue) .frame(width: 100, height: 100) .background { dragDetector(for: "blue") } } } } .gesture( DragGesture(coordinateSpace: .global) .onChanged { val in dragLocation = val.location } .onEnded { val in dragLocation = .zero dragInfo = " " } ) } }
Posted
by SergioDCQ.
Last updated
.
Post not yet marked as solved
0 Replies
315 Views
Am trying to figure out how to dismiss the iOS keyboard if my TextFields do not have focus. Obviously when clicking a button I can call a dismiss keyboard function. But what I wanted to learn was how to dismiss the keyboard of if the user hits return OR clicks off of the TextFields. Before I could figure out the "user hit return part" I got stuck at the user being able to click away from the TextFields. While I can add a onTapGesture to the text fields, I wonder if I can do something like detecting a tapGesture to the entire screen, so that if the user taps on any blank space I could call the dismiss keyboard function. import SwiftUI struct ContentView: View { @State var textField1 = "" @State var textField2 = "" @State var hasFocus = "No text field has focus" @FocusState var leftTyping : Bool @FocusState var rightTyping : Bool var body: some View { VStack { Text(hasFocus) .font(.largeTitle) HStack { TextField("left" , text: $textField1) .focused($leftTyping) .onChange(of: leftTyping) { if leftTyping == false, rightTyping == false { hideKeyboard() hasFocus = "No text field has focus" } else if leftTyping { hasFocus = "focus on left field" } } TextField("right", text: $textField2) .focused($rightTyping) .onChange(of: rightTyping) { if leftTyping == false, rightTyping == false { hideKeyboard() hasFocus = "No text field has focus" } else if rightTyping { hasFocus = "focus on right field" } } } Button ("steal focus"){ hideKeyboard() hasFocus = "No text field has focus" } .buttonStyle(.borderedProminent) .tint(.brown) .font(.largeTitle) .padding(10) .foregroundStyle(.white) } .padding() } func hideKeyboard() { UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) } } #Preview { ContentView() } Is there a way to do this?
Posted
by SergioDCQ.
Last updated
.
Post not yet marked as solved
1 Replies
312 Views
I hope this isn't too off-topic, but I'm in a bind My HD is so full that I can't download any new iOS' in Xcode. Actually, there's a lot I can't do. According to the storage part of System Details, Developer is over 100 GB. I have a huge external HD and would like to completely remove and clean Xcode, and the reinstall it on the external HD. 1 - Is this allowed? Some people say that all apps must be installed in the Applications folder. Checking the web I get both answers. 2 - If it is allowed, is there a way to properly clean out? Because every website I found that describes this procedure is touting their own cleanup app. Thank you
Posted
by SergioDCQ.
Last updated
.
Post marked as solved
4 Replies
16k Views
It's a small thing, but every time I open my current Xcode project the default iOS device to run my app on is my phone. Is there a way to change it to one of the simulators? i.e. iPhone Pro 11?
Posted
by SergioDCQ.
Last updated
.
Post marked as solved
1 Replies
405 Views
Within my SwiftUI view I have multiple view items, buttons, text, etc. Within the view, the user selects a ticket, and then clicks a button to upload it. The app then sends the ticket to my server, where the server takes time to import the ticket. So my SwiftUI app needs to make repeated URL calls depending on how far the server has gotten with the ticket. I thought the code below would work. I update the text to show at what percent the server is at. However, it only works once. I guess I thought that onAppear would work with every refresh since it's in a switch statement. If I'm reading my debugger correctly, SwiftUI recalls which switch statement was called last and therefore it views my code below as a refresh rather than a fresh creation. So is there a modifier that would get fired repeatedly on every view refresh? Or do I have to do all my multiple URL calls from outside the SwiftUI view? Something like onInitialize but for child views (buttons, text, etc.) within the main view? switch myNewURL.stage { case .makeTicket: Text(myNewURL.statusMsg) .padding(.all, 30) case .importing: Text(myNewURL.statusMsg) .onAppear{ Task { try! await Task.sleep(nanoseconds: 7000000000) print ("stage two") let request = xFile.makeGetReq(xUser: xUser, script: "getTicketStat.pl") var result = await myNewURL.asyncCall(request: request, xFile: xFile) } } .padding(.all, 30) case .uploadOriginal: Text(myNewURL.statusMsg) .padding(.all, 30) case .JSONerr: Text(myNewURL.statusMsg) .padding(.all, 30) }
Posted
by SergioDCQ.
Last updated
.
Post marked as solved
1 Replies
1.4k Views
Trying to to convert my old URL functionality to SwiftUI with async/await. While the skeleton below works, am puzzled as to why I must place my call to the method within a Task? When I don't use Task I get the error: Cannot pass function of type '() async -> Void' to parameter expecting synchronous function type From the examples I've seen, this wasn't necessary. So I either I've misunderstood something, or I am doing this incorrectly, and am looking for little but of guidance. Thank you Within my SwiftUI view: Button { Task { let request = xFile.makePostRequest(xUser: xUser, script: "requestTicket.pl") var result = await myNewURL.asyncCall(request: request) print("\(result)") } } From a separate class: class MyNewURL: NSObject, ObservableObject { func asyncCall(request: URLRequest) async -> Int { do { let (data, response) = try await URLSession.shared.data(for: request) guard let httpResponse = response as? HTTPURLResponse else { print("error") return -1 } if httpResponse.statusCode == 200 { ... } } catch { return -2 } return 0 } }
Posted
by SergioDCQ.
Last updated
.
Post not yet marked as solved
0 Replies
261 Views
I have a class, MyURL, from a UIKit app that I wrote that handles all my URL needs, uploads, downloads, GETS, POSTS, etc. I would like to use that class from within a SwiftUI view now. So the SwiftUI view that creates calls MyURL methods. And I would pass binding vars that would cause my SwiftUI view to update things such as statuses : percentage done, etc. My issue is, how can I properly declare that class, myURL, from within the SwiftUI view, so that it doesn't get redeclared every time the view updates. Should I declare the MyURL class in a view above it and pass it into the view that calls the MyUrl class? Would just like to do it the proper way. I wish I was better with terminology. Thank you struct ContentView: View { **var myURL = MyURL()** @State var proceed = false var body: some View { Button { myURL.pressed(proceed: $proceed) } label: { Text(proceed ? "pressed" : "not pressed") } } } class MyURL: NSObject, URLSessionDataDelegate,URLSessionTaskDelegate, URLSessionDelegate, URLSessionDownloadDelegate{ func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { } func pressed(proceed: Binding<Bool>) { print("\(proceed)") proceed.wrappedValue.toggle() } // Error received func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if let err = error { DispatchQueue.main.async { [self] in //code } } } // Response received func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: (URLSession.ResponseDisposition) -> Void) { completionHandler(URLSession.ResponseDisposition.allow) if let httpResponse = response as? HTTPURLResponse { xFile?.httpResponse = httpResponse.statusCode DispatchQueue.main.async { [self] in if httpResponse.statusCode != 200 { //code } } } } // Data received func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { if xFile?.httpResponse == 200 { DispatchQueue.main.async { [self] in //code } } //DispatchQueue.main.async } } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { let num : Float = Float(totalBytesWritten * 100) let den : Float = Float(totalBytesExpectedToWrite * 100) let percentDownloaded : Int = Int(num/den * 100) DispatchQueue.main.async { [self] in //code } } }
Posted
by SergioDCQ.
Last updated
.
Post not yet marked as solved
0 Replies
274 Views
Trying to create an app in SwiftUI that uses HTTP for "gets", "posts", "forms", et al. I cannot assign URLSessionDataDelegate,URLSessionTaskDelegate, URLSessionDelegate to a SwiftUI view. So my assumption is that I need to create a UIViewControllerRepresentable for a regular UIViewController and assign the delegates to that UIViewController I just need to know if this is the correct path to proceed with? Or is there some sort ion tie in that I cannot find using Google? Thank you
Posted
by SergioDCQ.
Last updated
.
Post not yet marked as solved
6 Replies
16k Views
Hello, Just starting to learn Xcode and I can test the first chapter's app on my iPhone if it's conncted via USB-C. The book walks me through the part where I can allow Xcode to connect to the iPhone via WiFi, just checking "Connect via Network."Yet Xcode cannot find my phone unless it's connected via USB. When I go to Devices that checkbox stays checked, unless I unplug the phone it which case that box doesn't even appear.And yes, they are both on the same WiFi, it's the only one I have and it's up and running.Any thoughs?
Posted
by SergioDCQ.
Last updated
.
Post marked as solved
2 Replies
2.1k Views
Am going through a SwiftUI course, so the code is not my own. When I migrated my @Bindings into @Published items in an @ObservableObject I started getting the following error: Publishing changes from within view updates is not allowed, this will cause undefined behavior. The warning occurs in the ScannerView which is integrated with the main view, BarcodeScannerView. It occurs when an error occurs, and scannerView.alertItem is set to a value. However, it does not occur when I am setting the value of scannerView.scannedCode, and as far as I can tell, they both come from the sample place, and are the same actions. There are tons of posts like mine, but I have yet to find an answer. Any thoughts or comments would be very appreciated. BarcodeScannerView import SwiftUI struct BarcodeScannerView: View { @StateObject var viewModel = BarcodeScannerViewModel() var body: some View { NavigationStack { VStack { ScannerView(scannedCode: $viewModel.scannedCode, typeScanned: $viewModel.typeScanned, alertItem: $viewModel.alertItem) .frame(maxWidth: .infinity, maxHeight: 300) Spacer().frame(height: 60) BarcodeView(statusText: viewModel.typeScanned) TextView(statusText: viewModel.statusText, statusTextColor: viewModel.statusTextColor) } .navigationTitle("Barcode Scanner") .alert(item: $viewModel.alertItem) { alertItem in Alert(title: Text(alertItem.title), message: Text(alertItem.message), dismissButton: alertItem.dismissButton) } } } } BarcodeScannerViewModel import SwiftUI final class BarcodeScannerViewModel: ObservableObject { @Published var scannedCode = "" @Published var typeScanned = "Scanned Barcode" @Published var alertItem: AlertItem? var statusText: String { return scannedCode.isEmpty ? "Not Yet scanned" : scannedCode } var statusTextColor: Color { scannedCode.isEmpty ? .red : .green } } ScannerView import SwiftUI struct ScannerView: UIViewControllerRepresentable { typealias UIViewControllerType = ScannerVC @Binding var scannedCode : String @Binding var typeScanned : String @Binding var alertItem: AlertItem? func makeCoordinator() -> Coordinator { Coordinator(scannerView: self) } func makeUIViewController(context: Context) -> ScannerVC { ScannerVC(scannerDelegate: context.coordinator) } func updateUIViewController(_ uiViewController: ScannerVC, context: Context) { } final class Coordinator: NSObject, ScannerVCDelegate { private let scannerView: ScannerView init(scannerView: ScannerView) { self.scannerView = scannerView } func didFind(barcode: String, typeScanned: String) { scannerView.scannedCode = barcode scannerView.typeScanned = typeScanned print (barcode) } func didSurface(error: CameraError) { switch error { case .invalidDeviceinput: scannerView.alertItem = AlertContext.invalidDeviceInput case .invalidScannedValue: scannerView.alertItem = AlertContext.invalidScannedValue case .invalidPreviewLayer: scannerView.alertItem = AlertContext.invalidPreviewLayer case .invalidStringObject: scannerView.alertItem = AlertContext.invalidStringObject } } } }
Posted
by SergioDCQ.
Last updated
.
Post not yet marked as solved
0 Replies
476 Views
I have this long kludgy bit of code that works. I've outlined it below so as not to be confusing as I have no error within my code. I just need to know if there's a method that already exists to copy a specific part of an AVAudioPCMBuffer to a new AVAudioPCMBuffer? So if I have an AVAudioPCMBuffer of 10,000 frames, and I just want frames 500 through 3,000 copied into a new buffer (formatting and all) without altering the old buffer...is there a method to do this? My code detects silent moments in an audio recording I currently read an audio file into an AVAudioPCMBuffer (audBuffOne) I loop through the buffer and detect the starts and ends of silence I record their positions in an array This array holds what frame position I detect voice starting (A) and which frame position the voice ends (B), with some padding of course ... new loop ... I loop through my array to go through each A and B framePositions Using the sample size from the audio file's formatting info, I create a new AVAudioPCMBuffer (audBuffTwo) large enough to hold from A to B and having the same formatting as audBuffOne I go back to audBuffOne Set framePosition to on the audio file to A Read into audBuffTwo for there proper length to reach frame B Save audBuffTwo to a new file ...keep looping
Posted
by SergioDCQ.
Last updated
.