Post

Replies

Boosts

Views

Activity

Not sure why Swift is giving me a "Cannot find 'xFile' in scope" error
I have the following structure : struct XFile : Codable { ...variables here init(fileUrl: URL, key: String) { ... } Then in another class I am trying the following: class UploadTask { var xfile: XFile var inProgress = false init(file: URL) { xFile = XFile(fileUrl: file, key: "filename") } } If typed as above Xcode gives me the following error: Cannot find 'xFile' in scope If I remove the xFile= part, Xcode give me the following warning and error: Result of 'XFile' initializer is unused Return from initializer without initializing all stored properties Obviously I am breaking some rule, just not sure what it is.
2
0
857
Apr ’22
Am unable to receive HTTP responses with UIViewController set as URLSessionDelegate
This question is also, here, one StackOverflow. But it's only gotten 8 views, and I am stuck till I find out what am I doing wrong. I am able to create a URLSesion, build a request with a file to upload and successfully call it from my app. On my server side, the proper script is called, uploaded file is saved, etc,. However, I am not receiving the HTTP responses, data, etc. Actually had this working without the delegate, when the HTTP response functions were within the task itself. But am now trying to expand functionality and am missing something while trying implement the delegate. The trimmed code is below, and it all works, with the exception of setting up UIViewController as the URLSession delegate. Just trying to figure out why my UIViewController is not receiving the HTTP responses. Below is the code for: UIViewController Class which creates the upload session (UploadService) Extension for UIViewController which I want to use to process the responses How the previous task looked, when it worked. Before I tried to implement the delegate. UIViewController class UploadInv : UIViewController { var xFile : XFile? ...create UI.... let uploadService = UploadService() lazy var uploadSession: URLSession = { let configuration = URLSessionConfiguration.default return URLSession(configuration: configuration, delegate: self, delegateQueue: .main) }() override func viewWillAppear(_ animated: Bool) { ... } override func viewDidLoad() { super.viewDidLoad() uploadService.uploadSession = uploadSession ... code the lays out all buttons, labels, etc... } @objc func buttonAction(sender: UIButton!) { guard let theButton = sender else { return} let myTag = theButton.tag switch myTag { //button to start upload case ButtType.up.rawValue: uploadService.start(upFile: xFile!, script: "uploadOrig.pl", upLoadInvClass: self) uploadService.task?.resume() //button to select file to upload case ButtType.file.rawValue: ... file xFile with file info } } UploadService class UploadService { var task: URLSessionUploadTask? var uploadSession = URLSession.shared func start(upFile: XFile, script: String, upLoadInvClass: UploadInv) { var request = upFile.makeUrlReq(upFile: upFile, script: script) self.task = uploadSession.uploadTask(with: request, from: request.httpBody! ) } } extension extension UploadInv: UIDocumentPickerDelegate, URLSessionDelegate { func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { ... file xFile info for upload .... ... http request created .... } // Below are the three simple functions which I would handle // responses the server, but these never seem to get called. func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if let err = error { print("Error: \(err.localizedDescription)") } } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: (URLSession.ResponseDisposition) -> Void) { print("didReceive response") completionHandler(URLSession.ResponseDisposition.allow) } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { print("didReceive data") if let responseText = String(data: data, encoding: .utf8) { print(responseText) } } } Pre-Delegate model which worked class UploadService { var uploadSession = URLSession.shared func start(upFile: XFile, script: String, upLoadInvClass: UploadInv) { var request = upFile.makeUrlReq(upFile: upFile, script: script) uploadSession.uploadTask(with: request, from: request.httpBody ) { (data, response, error) in if let response = response { upLoadInvClass.upResp(resp: response) } if let error = error { upLoadInvClass.upErr(error: error) } if let data = data { upLoadInvClass.upData(data: data) } }.resume() } }
3
0
1.1k
May ’22
Is there an order for response, data, and error in URLSession delegates?
_Posted this here, on Stackoverflow. But after 2+ weeks got only 10 views and no responses. _ I have my URLSession delegates working, but am curious about the order I get back response, data, and error. Right now am testing purposeful errors on my server side, so I can check the response if it's not 200. If it's not, I do not need to process the data, etc. So I could use a flag, but have to make sure that I'l always get response, data, and error in a specific order? Does such an order exist? extension UploadInv: UIDocumentPickerDelegate, URLSessionDataDelegate,URLSessionTaskDelegate, URLSessionDelegate { // Error received func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if let err = error { print("Error: \(err.localizedDescription)") } } // Response received func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: (URLSession.ResponseDisposition) -> Void) { completionHandler(URLSession.ResponseDisposition.allow) DispatchQueue.main.async { [self] in if let httpResponse = response as? HTTPURLResponse { if httpResponse.statusCode != 200 { DispatchQueue.main.async { [self] in self.myStatus.text = "Error \(String(httpResponse.statusCode))" myBackButt.isEnabled = true } } } } } // Data received func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { DispatchQueue.main.async { [self] in
3
0
1.1k
May ’22
Changing my entities in CoreData gave me a NSCocoaErrorDomain Code=134140 and I can't go back
Updated info below, in bold. I went and changed one of the entities in the CoreData of my app. For all my entities I have them selected as "Manual" for Codegen So I deleted all four files (for two entities), cleaned the build folder, regenerated the CoreData files with Editor -> Create NSManagedObject Subclass. Now every time I run the app I get a fatalError in the following code in the AppDelegate: lazy var persistentContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: “Invoice_Gen") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() The error code being [error] error: addPersistentStoreWithType:configuration:URL:options:error: returned error NSCocoaErrorDomain (134140) Even if I remove the files for the CoreData entities, and comment out anything related to them code wise, I will still get this crash. If someone has any idea of whether I have to delete something else, or am whatever I would so appreciate it. This one has me more stumped than anything before it. The change I made was to turn one of the entities' attribute from String to Int When I changed it back, everything works. So from my research on Google there is something about the mapping model. But I can not find it at all.
1
0
1.6k
Jun ’22
How can I find my app created log on my iPhone?
I am using the code below to create my own debug log for my app. On the simulator, I have no problem viewing that log. I simply print out the documents directory in the debugger, then open it in my finder. However I do not know how to access the created log on my iPhone itself. Even if I go to Window -> Devices and Simulator's, when I look at my app's container it's empty. Although I would like to be able to access the file from any actual device in the future. Am I using the wrong directory? I even used allDomainsMask in place of userDomainMask below, but to no avail. debugFileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("myApp.log") if let handle = try? FileHandle(forWritingTo: dbClass.debugFileURL!) { handle.seekToEndOfFile() // moving pointer to the end handle.write(text.data(using: .utf8)!) // adding content handle.closeFile() // closing the file } else { try! text.write(to: dbClass.debugFileURL!, atomically: false, encoding: .utf8) }
1
0
521
Jul ’22
How can I get the text of a label using the new UIContentConfiguration
Am trying to port away from .textLabel.text, as per Apple but I can't seem to find the way to get the text I set. I now set my cells this way: let cell = UITableViewCell() var config = cell.defaultContentConfiguration() config.text = dbClass.nameList[indexPath.row].clientName config.textProperties.color = .black config.textProperties.alignment = .center cell.contentConfiguration = config But when I try to get the text of a selected cell (once the user hits the OK button) I can't seem to reverse engineer how to get the text. let cell = myClientList.cellForRow(at: myInvsList.indexPathForSelectedRow!) let config = cell?.contentConfiguration dbClass.curMasterinvList = ?????? (can't find what property to read here I even tried let config = cell?.defaultContentConfiguration() Hoping that the text would be in there, but the text there is blank, so am assuming that's just the standard config before I've changed it. I have Googled as much as possible, but can't seem to find this very simple need.
4
0
1.1k
Jul ’22
Where can I call register(_:forCellReuseIdentifier:) if I am not using a UITableViewController?
Currently I am placing a UITableView inside my UIViewController, with multiple other items. I am not using a UITableViewController. However I am unable to register the identifier "masterlist", or should I say I am not sure where I can register it. I am not using storyboard, and if I am still to register it in my UIViewController's viewDidLoad, I am unable to figure out the proper syntax. Is this something I can do? class BeginNewCustomer: UIViewController { let myList = createTblView() override func viewDidLoad() { super.viewDidLoad() myList.delegate = self myList.dataSource = self } func createTblView() -> UITableView { let myTable = MyTableView(frame: CGRect(x: 0, y: 0, width: 0, height: 0 )) myTable.backgroundColor = .white return myTable } extension BeginNewInv: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dbClass.invsList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() // let cell = tableView.dequeueReusableCell(withIdentifier: "masterlist", for: indexPath) var config = cell.defaultContentConfiguration() .... fill the configuration cell.contentConfiguration = config return cell } }
3
0
831
Jul ’22
Detecting background volume level in Swift
Am trying to distinguish the differences in volumes between background noise, and someone speaking in Swift. Previously, I had come across a tutorial which had me looking at the power levels in each channel. It come out as the code listed in Sample One which I called within the installTap closure. It was ok, but the variance between background and the intended voice to record, wasn't that great. Sure, it could have been the math used to calculate it, but since I have no experience in audio data, it was like reading another language. Then I came across another demo. It's code was much simpler, and the difference in values between background noise and speaking voice was much greater, therefore much more detectable. It's listed here in Sample Two, which I also call within the installTap closure. My issue here is wanting to understand what is happening in the code. In all my experiences with other languages, voice was something I never dealt with before, so this is way over my head. Not looking for someone to explain this to me line by line. But if someone could let me know where I can find decent documentation so I can better grasp what is going on, I would appreciate it. Thank you Sample One func audioMetering(buffer:AVAudioPCMBuffer) { // buffer.frameLength = 1024 let inNumberFrames:UInt = UInt(buffer.frameLength) if buffer.format.channelCount > 0 { let samples = (buffer.floatChannelData![0]) var avgValue:Float32 = 0 vDSP_meamgv(samples,1 , &avgValue, inNumberFrames) var v:Float = -100 if avgValue != 0 { v = 20.0 * log10f(avgValue) } self.averagePowerForChannel0 = (self.LEVEL_LOWPASS_TRIG*v) + ((1-self.LEVEL_LOWPASS_TRIG)*self.averagePowerForChannel0) self.averagePowerForChannel1 = self.averagePowerForChannel0 } if buffer.format.channelCount > 1 { let samples = buffer.floatChannelData![1] var avgValue:Float32 = 0 vDSP_meamgv(samples, 1, &avgValue, inNumberFrames) var v:Float = -100 if avgValue != 0 { v = 20.0 * log10f(avgValue) } self.averagePowerForChannel1 = (self.LEVEL_LOWPASS_TRIG*v) + ((1-self.LEVEL_LOWPASS_TRIG)*self.averagePowerForChannel1) } } Sample Two private func getVolume(from buffer: AVAudioPCMBuffer, bufferSize: Int) -> Float { guard let channelData = buffer.floatChannelData?[0] else { return 0 } let channelDataArray = Array(UnsafeBufferPointer(start:channelData, count: bufferSize)) var outEnvelope = [Float]() var envelopeState:Float = 0 let envConstantAtk:Float = 0.16 let envConstantDec:Float = 0.003 for sample in channelDataArray { let rectified = abs(sample) if envelopeState < rectified { envelopeState += envConstantAtk * (rectified - envelopeState) } else { envelopeState += envConstantDec * (rectified - envelopeState) } outEnvelope.append(envelopeState) } // 0.007 is the low pass filter to prevent // getting the noise entering from the microphone if let maxVolume = outEnvelope.max(), maxVolume > Float(0.015) { return maxVolume } else { return 0.0 } }
1
0
2.7k
Jul ’22
Do I have to build in support for user scrolling through a UITextView object?
I am trying to add a UITextView within my app to output data to. Naturally the data will eventually be bigger than the size of the UITextView, and the view is a set size. So I would like the user to be able to scroll through its content. However, I cannot scroll through the content in the app. Am I supposed to build the scrolling function myself? Seems weird that I would have to do that, but I cannot seem to find the answer to this on the web. I’ve also noticed that no vertical scroll at shows up when the text count is larger than the size of the object, which makes me wonder if I am missing a property or two. func createStatusField() -> UITextView { let myStatus = UITextView(frame: CGRect(x: 50, y: 50, width: 100, height: 300)) myStatus.autocorrectionType = .no myStatus.text = "hello there" myStatus.backgroundColor = .secondarySystemBackground myStatus.textColor = .secondaryLabel myStatus.font = UIFont.preferredFont(forTextStyle: .body) myStatus.layer.zPosition = 1 myStatus.isScrollEnabled = true myStatus.showsVerticalScrollIndicator = true return myStatus }
3
0
695
Aug ’22
Looking for tutorial to write apps that receive push notifications (i.e. Messaging)
I am looking for a proper tutorial on how to write let's say a messaging app. in other words the user doesn't have to run Messaging to get messages. I would like to build that type of structured app. I realize that "push notifications" appear the way to go. But at this point I still can't find an decent tutorial that seems to cover all the bases. Thank you
1
0
627
Nov ’22
How can I open an audio file into a buffer that I can read pieces of said buffer?
I would like to open an audio file on my iOS device and remove long silences. I already have the code for calculating volumes so am not pasting that here. What I am unsure of "how to do" is: While I believe that I have the proper code to read the file below, I am unsure as to how to read it in proper pieces to I can later get the volume of each piece. I realize that this might be a situation of calculating the size of frames and whatnot. But I am totally green when it comes to audio. I would seriously appreciate any guidance. guard let input = try? AVAudioFile(forReading: url) else { return nil } guard let buffer = AVAudioPCMBuffer(pcmFormat: input.processingFormat, frameCapacity: AVAudioFrameCount(input.length)) else { return nil } do { try input.read(into: buffer) } catch { return nil }
2
0
918
Dec ’22
Can I determine the time length of an AVAudioPCMBuffer's individual frame?
I am looping through an audio file, below is my very simple code. Am looping through 400 frames each time, but I picked 400 here as a random number. I would prefer to read in by time instead. Let's say a quarter of second. So I was wondering how can I determine the time length of each frame in the audio file? I am assuming that determining this might differ based on audio formats? I know almost nothing about audio. var myAudioBuffer = AVAudioPCMBuffer(pcmFormat: input.processingFormat, frameCapacity: 400)! guard var buffer = AVAudioPCMBuffer(pcmFormat: input.processingFormat, frameCapacity: AVAudioFrameCount(input.length)) else { return nil } var myAudioBuffer = AVAudioPCMBuffer(pcmFormat: input.processingFormat, frameCapacity: 400)! while (input.framePosition < input.length - 1 ) { let fcIndex = ( input.length - input.framePosition > 400) ? 400 : input.length - input.framePosition try? input.read(into: myAudioBuffer, frameCount: AVAudioFrameCount(fcIndex)) let volUme = getVolume(from: myAudioBuffer, bufferSize: myAudioBuffer.frameLength) ...manipulation code }
1
0
1.6k
Dec ’22
Why do I get a "Publishing changes from within view updates is not allowed" when moving my @Bindings to @Published in an @ObservableObject?
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 } } } }
4
0
5.1k
Mar ’23