Dive into the world of programming languages used for app development.

All subtopics

Post

Replies

Boosts

Views

Activity

Swift Package Manager not building external dependencies correctly
I have created my own SPM through File -> New -> Package Package.swift looks like: // swift-tools-version: 5.10 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "MyPackage", platforms: [.iOS(.v16), .macCatalyst(.v16), .macOS(.v14)], products: [.library(name: "MyPackage", targets: ["MyPackage"]),], dependencies: [ .package(path: "../external-package") ], targets: [ .target(name: "MyPackage", path: "Sources"), .testTarget(name: "MyPackageTests", dependencies: ["MyPackage"]), ] ) When I run swift build the error says: '.../MyPackage/.build/arm64-apple-macosx/debug/external-package.build/external-package-Swift.h' not found and surely, when I go to directory: .../MyPackage/.build/arm64-apple-macosx/debug/external-package.build/ there are only 2 files in there: module.modulemap & output-file-map.json All source files from external-package are missing, therefore swift build fails. The only solution I've found is to copy external-package.build folder manually into: '.../MyPackage/.build/arm64-apple-macosx/debug/` What am I missing here? Should swift build create those files in there, or they should be resolved somehow differently? Note: external-package is not in any way unique, this happens to any added dependency I'm running on macOS 14.6.1 on Apple Silicon M1 Pro with Xcode 15.4
1
0
415
Aug ’24
How does the threshold in DeviceActivityEvent work
Hey everyone, I'm working on implementing an AppLimit, where after accumulating x minutes of Screen Time for an app, it should be blocked. It works fine on the first day, but stops functioning correctly on subsequent days. What I'm Doing I start a 24/7 schedule with a DeviceActivityEvent that has a specified Screen Time threshold. In my DeviceActivityMonitor, I'm reacting to the eventDidReachThreshold. Once the accumulated time is reached, the app is blocked. This works as expected on the first day. Issues I'm Experiencing / Questions Second Day Issue: On the second day, the app is no longer blocked after the Screen Time threshold is reached, even though it worked on the first day. This leads me to suspect that a DeviceActivityEvent is "consumable". Is this correct? Pre-existing Screen Time Issue: If a user has already surpassed the Screen Time threshold before monitoring starts, the app isn't blocked once the schedule is set up. This leads to 2 issues: I would expect that the accumulated amount of time after starting the schedule would result in the call of eventDidReachThreshold. But it is never called It could also be the case that the previously accumulated time is being kept in mind, but that would mean the apps should be blocked, which isn't the case. Does the threshold account for accumulated Screen Time before the schedule begins? I haven't tested setting a limit of 10 minutes, accumulating 3 minutes of Screen Time, then starting the schedule and accumulating the remaining time, but I'm curious if anyone has encountered this behavior. Does anyone have an explanation for this behavior? Any help would be greatly appreciated!
1
0
434
Aug ’24
MDM - Getting location when app is killed
Dear, We are working on a solution that uses MDM to manage devices and create features for our users. As part of this, we want to implement a feature that retrieves the device's location even when the app is closed (killed). Is there a way to achieve this? Since we are an MDM solution, is there a function available within MDM that allows us to obtain this information? We are considering implementing the Location Push Service Extension. If we do, will we be able to receive latitude and longitude even if the app is closed?
0
0
197
Aug ’24
Condensing HTTP request functions
Hi, For HTTP requests, I have the following function: func createAccount(account: Account, completion: @escaping (Response) -> Void) { guard let url = URL(string: "http://localhost:4300/account") else { return } var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") guard let encoded = try? JSONEncoder().encode(account) else { print("Failed to encode request") return } request.httpBody = encoded URLSession.shared.dataTask(with: request) { (data, response, error) in guard let data = data else { return } do { let resData = try JSONDecoder().decode(Response, from: data) DispatchQueue.main.async { completion(resData) } } catch let jsonError as NSError { print("JSON decode failed: \(jsonError)") } }.resume() } Because various HTTP requests use different body structs and response structs, I have a HTTP request function for each individual HTTP request. How can I condense this into one function, where the passed struct and return struct are varying, so I can perhaps pass the struct types in addition to the data to the function? Any guidance would be greatly appreciated.
0
0
219
Aug ’24
Build iOS 18 with Swift 5.10
I noticed that running my app in Xcode 16 crashes often. It seems this is due to the strictness Swift 6 adds at runtime. Even after making sure the Swift Language Mode is 5 for the main target and all modules. I'm migrating to Swift 6 but I probably won't be done before iOS 18 drops so my question is. Can I still ship the app supporting iOS 18 using Xcode 15.4 and Swift 5.10?
2
1
529
Aug ’24
IOS 18 Public Beta issues
I can’t merge phone calls, people on the phone cannot hear meand I can’t hear them Alarm doesn’t work sound sometimes. I need to reboot the phone to make sure it works I need to reboot the phone to make sure it works 3. Cannot update customize wallpaper for home screen. You can update lock screen but not home screen. You can update lock screen but not home screen.
1
0
179
Aug ’24
Polar H10 ECG reading
There are some reliable and affordable Polar H10 ECG reader apps available on the App Store: I’ve been using one for a couple of years. However, I recently needed to incorporate an ECG capability into an app that already uses the Polar H10 for RR Interval monitoring, but the documentation online for Polar ECG is scarce and sometimes incorrect. Polar provides an SDK, but this covers many different devices and so is quite complex. Also, it’s based on RxSwift - which I prefer not to use given that my existing app uses native Swift async and concurrency approaches. I therefore offer this description of my solution in the hope that it helps someone, somewhere, sometime. The Polar H10 transmits ECG data via Bluetooth LE as a stream of frames. Each frame is length 229 bytes, with a 10 byte leader and then 73 ECG data points of 3 bytes each (microvolts as little-endian integer, two’s complement negatives). The leader’s byte 0 is 0x00, bytes 1 - 8 are a timestamp (unknown epoch) and byte 9 is 0x00. The H10’s sampling rate is 130Hz (my 2 devices are a tiny fraction higher), which means that each frame is transmitted approximately every half second (73/130). However, given the latencies of bluetooth transmission and the app’s processing, any application of a timestamp to each data point should be based on a fixed time interval between each data point, i.e. milliseconds interval = 1000 / actual sampling rate. From my testing, the time interval between successive frame timestamps is constant and so the actual sampling interval is that interval divided by 73 (the number of samples per frame). I’ve noticed, with both the 3rd party app and my own coding, that for about a second (sometimes more) the reported voltages are very high or low before settling to “normal” oscillation around the isoelectric line. This is especially true when the sensor electrode strap has only just been placed on the chest. To help overcome this, I use the Heart Rate service UUID “180D” and set notify on characteristic "2A37" to get the heart rate and RR interval data, of which the first byte contains flags including a sensor contact flag (2 bits - both set when sensor contact is OK, upon which I setNotifyValue on the ECG data characteristic to start frame delivery). Having discovered your Polar H10, connected to it and discovered its services you need to discover the PMD Control Characteristic within the PMD Service then use it to request Streaming and to request the ECG stream (there are other streams). Once the requests have been accepted (didWriteValueFor Characteristic) then you start the Stream. Thereafter, frames are delivered by the delegate callback func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) for the characteristic.uuid == pmdDataUUID The following code snippets, the key aspects of the solution, assume a working knowledge of CoreBluetooth. Also, decoding of data (code not provided) requires a knowledge of byte and bit-wise operations in Swift (or Objective-C). // CBUUIDs and command data let pmdServiceUUID = CBUUID.init( string:"FB005C80-02E7-F387-1CAD-8ACD2D8DF0C8" ) let pmdControlUUID = CBUUID.init( string:"FB005C81-02E7-F387-1CAD-8ACD2D8DF0C8" ) let pmdDataUUID = CBUUID.init( string:"FB005C82-02E7-F387-1CAD-8ACD2D8DF0C8" ) let reqStream = Data([0x01,0x02]) let reqECG = Data([0x01,0x00]) let startStream = Data([0x02, 0x00, 0x00, 0x01, 0x82, 0x00, 0x01, 0x01, 0x0E, 0x00]) // Request streaming of ECG data func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) if service.uuid == pmdServiceUUID { for pmdChar in service.characteristics! { if pmdChar.uuid == pmdControlUUID { peripheral.setNotifyValue(true, for: pmdChar) peripheral.writeValue(reqStream, for: pmdChar, type: .withResponse) peripheral.writeValue(reqECG, for: pmdChar, type: .withResponse) } } } } // Request delivery of ECG frames - actual delivery subject to setNotify value func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { // this responds to the reqStream and reqECG write values if error != nil { print("**** write error") return } if ecgStreamStarted { return } // I use a flag to prevent extraneous stream start commands guard let charVal = characteristic.value else { return } if charVal[0] == 0xF0 && charVal[1] == 0x01 { peripheral.writeValue(startStream, for: characteristic, type: .withResponse) ecgStreamStarted = true } } For “live” charting, I create an array of data points, appending each frame’s set on arrival, then provide those points to a SwiftUI View with a TimeLineView(.periodic(from: .now, by:actual sampling interval)) and using Path .addlines with the Y value scaled appropriately using GeometryReader. So far, I’ve found no way of cancelling such a TimeLineView period, so any suggestions are welcome on that one. An alternative approach is to refresh a SwiftUI Chart View on receipt and decoding of each frame, but this creates a stuttered appearance due to the approximately half-second interval between frames. Regards, Michaela
0
0
482
Aug ’24
Develop in Swift - SwiftUI update?
I've been relishing Develop in Swift: Fundamentals as an introduction to Swift. It's wonderful! Having limited time, and ultimately targeting visionOS development, I've reached a point where any UIKit content feels like a distraction from my goals. Hence I'm switching to SwiftUI Bootcamp by Swiftful Thinking on YouTube, SwiftUI Concepts Tutorials, and SwiftUI Tutorials by Apple. Is there any official word on updates to the Develop in Swift series? Failing that, any other recommendations on how to bridge between Fundamentals and visionOS development?
2
0
417
Aug ’24
Open specific web extension in safari settings (iOS/App/Swift)
Hi all, I have a problem with trying to use UIApplication.shared.canOpenURL to open a specific web extension in the safari settings. When executing the code below the safari extension menu is shown but not the settings for the specific extension: if let url = URL(string: "App-prefs:SAFARI&path=WEB_EXTENSIONS/NAME_OF_EXTENSION") { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } However, the weird thing is that when executing the above I can see some kind of an event that looks like it tries to click the specific extension. Furthermore, if I keep the settings open and tries to execute the code again it actually works, and the specific web extension's settings is open. Hope someone can help.
0
0
296
Aug ’24
xCode Project with Breakpoints and .app Crashing?
I recently created a project, originally in xCode 13.3 if i am not miistaken. Then i update it to 13.4 then update to mac os 15.6 as well. Previously the project worked fine, but then i notice if i activate breakpoints the projects stopped when i run it in xCode but it worked fine like before, without breakpoints activated. Also, when i build a .app of the project, the .app crashed exactly when the breakpoints previously stopped. I am very confused on how to continue, would like to get help from anyone regarding the issue. From what i can gather from the breakpoints and crash report, it's got something about UUIID registration? AV foundation? I am so confused. Please Help! Thanks.
0
0
312
Aug ’24
ModelContainer working but ModelContext not finding items with SwiftDta
I am trying to count a database table from inside some of my classes. I am tying to do this below **(My problem is that count1 is working, but count2 is not working.) ** class AppState{ private(set) var context: ModelContext? .... func setModelContext(_ context: ModelContext) { self.context = context } @MainActor func count()async{ let container1 = try ModelContainer(for: Item.self) let descriptor = FetchDescriptor<Item>() let count1 = try container1.mainContext.fetchCount(descriptor) let count2 = try context.fetchCount(descriptor) print("WORKING COUNT: \(count1)") print("NOTWORKING COUNT: \(count2) -> always 0") } I am passing the context like: ... @main @MainActor struct myApp: App { @State private var appState = AppState() @Environment(\.modelContext) private var modelContext WindowGroup { ItemView(appState: appState) .task { appState.setModelContext(modelContext) } } .windowStyle(.plain) .windowResizability(.contentSize) .modelContainer(for: [Item.self, Category.self]) { result in ... } Can I get some guidance on why this is happening? Which one is better to use? If I should use count2, how can I fix it? Is this the correct way to search inside an application using SwiftData ? I don't wanna search using the View like @Query because this operation is gonna happen on the background of the app.
1
0
359
Aug ’24
Best way to pause DeviceActivitySchedule
Hi everyone, I'm currently working with the Screen Time API, specifically trying to figure out the best way to pause an active, repeating schedule without disrupting future schedules. Here's the scenario: I have a repeating schedule set from 10:00 AM to 8:00 PM daily. If I need to pause the schedule temporarily, my current approach involves stopping monitoring, clearing all restrictions, and then setting a new schedule for the remaining time after the pause. However, this method cancels the repeating schedule entirely, which causes issues when the schedule is supposed to restart the next day at 10:00 AM. Instead, it starts after the pause time, which isn’t what I want. Challenges I'm Facing: Maintaining Repeating Schedules: How can I pause the schedule in a way that ensures it resumes correctly the next day at the intended time (10:00 AM)? DeviceActivityMonitor Logic: Is there a way to deactivate and reactivate the schedule through the DeviceActivityMonitor without fully stopping the monitoring? Ideally, I'd like to retain the original schedule, pause it, and then resume it seamlessly after the pause. What I’ve Tried So Far: I’ve attempted to store the necessary data in the App Groups shared container as a local file. In the DeviceActivityMonitor, I used the schedule's name to identify and retrieve the saved object, planning to use this data to reapply the shielding after the pause. Unfortunately, this approach exceeds the 6MB memory limit of the extension, which is another roadblock. Given these issues, I’m unsure how to move forward. Are there any best practices or alternative approaches that could help manage this situation more effectively? Any insights or suggestions would be greatly appreciated! Thanks in advance for your help.
1
0
491
Aug ’24
Stack feature not working as per plan.
Good Morning/Afternoon/Evening. I'm trying to build a code with a background bar (grey) and above it, we have a ProgressiveBar that starts full and empties as time passes. To be able to stack the elements one above the other I'm trying to use the Zstack function, as shown on the code below, but when simulating the code the progressiveBar is always, on the iPhone screen, showing on top of the background bar, and not above as desired. Could you please review the code below and let me know what I'm missing? `var body: some View { ZStack(alignment: .leading) { // Background bar RoundedRectangle(cornerRadius: 10) .fill(Color.gray.opacity(0.3)) .frame(height: barHeight) // Set height to the specified barHeight // Progress bar GeometryReader { geometry in RoundedRectangle(cornerRadius: 10) .fill(barColor) .frame(width: CGFloat(progress) * geometry.size.width, height: barHeight) .animation(.linear(duration: 1), value: progress) } .cornerRadius(10) // Icon and label HStack { Image(systemName: icon) .foregroundColor(.black) .font(.system(size: 28)) // Increased size .padding(.leading, 8) Spacer() Text(timeString(from: duration * Double(progress))) .foregroundColor(.black) .bold() .font(.system(size: 24)) // Increased size .padding(.trailing, 8) } .frame(width: UIScreen.main.bounds.width * 0.9, height: barHeight) .zIndex(1) // Ensure the HStack is on top } .padding(.horizontal)
3
0
282
Aug ’24
Xcode 16 beta 5 MainActor errors in a Swift 6 project while working in beta 4
After updating to Xcode 16.0 beta 5 (16A5221g) on macOS Sonoma 14.6 I am getting lots of errors like: Main actor-isolated property '[property name]' can not be mutated from a nonisolated context in classes that are marked as @MainActor at the class level, e.g.: @MainActor final class MyClass: AnotherClass { ... } The project uses Swift 6 and there are no errors in Xcode 16 beta 4. I tried restarting, clearing Derived Data, cleaning build folder... Anyone else encountering this issue with beta 5?
1
1
508
Aug ’24
Swiftdata with Date
Dear all, I'm going out of mind with the following issue. I have a view where I'm selecting a date through a datepicker. Then I'm inserting some other data and then I'm trying to save, see private func saveTraining(). But the date which is used to save the training is always one day before the selected date and more than this, I'm not able to save it without time. As I have then a calendar where the saved trainings need to be displayed, I'm not able to match it. Did anybody already face this issue? How can I solve it? I'm reporting here the code of the view where you can also find the checks I put to verify values/ dates: import SwiftData import AppKit struct AddTrainingView: View { @Environment(\.modelContext) private var context @Binding var isAddingTraining: Bool @ObservedObject var season: Season @Binding var selectedDate: Date @State private var trainingStartTime = Date() @State private var trainingEndTime = Date() @State private var trainingConditionalGoal = "" @State private var trainingTacticalGoal = "" @State private var trainingExercises: [TrainingExercise] = [] @State private var showExercisePicker = false @State private var currentTraining: Training? init(isAddingTraining: Binding<Bool>, selectedDate: Binding<Date>, season: Season, currentTraining: Training? = nil) { self._isAddingTraining = isAddingTraining self._selectedDate = selectedDate self.season = season self._currentTraining = State(initialValue: currentTraining) if let training = currentTraining { self._trainingStartTime = State(initialValue: training.startTime) self._trainingEndTime = State(initialValue: training.endTime) self._trainingConditionalGoal = State(initialValue: training.conditionalGoal) self._trainingTacticalGoal = State(initialValue: training.tacticalGoal) self._trainingExercises = State(initialValue: training.trainingExercises) } } var body: some View { VStack(alignment: .leading, spacing: 16) { Text("Aggiungi Allenamento") .font(.title) .bold() .padding(.top) VStack(alignment: .leading) { Text("Data allenamento:") DatePicker("", selection: $selectedDate, displayedComponents: .date) .datePickerStyle(.field) } .padding(.bottom, 10) ... Button("Salva") { saveTraining() isAddingTraining = false dismiss() } .buttonStyle(.borderedProminent) .tint(.blue) Button("Visualizza PDF") { createPDF() } .buttonStyle(.borderedProminent) .tint(.blue) Spacer() } .padding(.bottom) } .padding() .frame(maxWidth: .infinity, maxHeight: .infinity) } private func saveTraining() { // Creiamo un'istanza del calendario corrente var calendar = Calendar.current calendar.timeZone = TimeZone.current // Assicuriamoci di utilizzare il fuso orario locale // Estrarre solo i componenti di data dalla data selezionata let components = calendar.dateComponents([.year, .month, .day], from: selectedDate) // Creiamo una nuova data con i soli componenti di anno, mese e giorno guard let truncatedDate = calendar.date(from: components) else { print("Errore nella creazione della data troncata") return } // Stampa di debug per verificare la data selezionata e quella troncata print("Data selezionata per l'allenamento: \(selectedDate)") print("Data troncata che verrà salvata: \(truncatedDate)") let newTraining = Training( date: truncatedDate, startTime: trainingStartTime, endTime: trainingEndTime, conditionalGoal: trainingConditionalGoal, tacticalGoal: trainingTacticalGoal, season: season ) // Verifica che la data sia correttamente impostata print("Data che verrà salvata: \(newTraining.date)") newTraining.trainingExercises = trainingExercises context.insert(newTraining) do { try context.save() print("Allenamento salvato correttamente.") } catch { print("Errore nel salvataggio: \(error.localizedDescription)") } } private var dateFormatter: DateFormatter { let formatter = DateFormatter() formatter.dateStyle = .short return formatter } private var timeFormatter: DateFormatter { let formatter = DateFormatter() formatter.timeStyle = .short return formatter } } } Example: when I'm selecting 2023-08-21, the debugger retrieves me following data: Data selezionata per l'allenamento: 2023-08-20 22:00:00 +0000 Data troncata che verrà salvata: 2023-08-20 22:00:00 +0000 Data che verrà salvata: 2023-08-20 22:00:00 +0000 Allenamento salvato correttamente.
3
0
690
Aug ’24
Does objc_setAssociatedObject() work reliably when used with "bridgeable" Core Foundation types?
I'm investigating an odd problem that surfaced with macOS Sequoia related to CoreGraphics (CGColorSpaceCreateWithICCData()). I couldn't find a reliable way to track the lifetime (retain/releases) of a CGColorSpaceRef (any pointers appreciated) so I was hoping to use objc_setAssociatedObject() to attach an instance of my own class that would be deallocated when the "owning" CGColorSpaceRef is deallocated. In this way I could set a breakpoint on my own code, presumably invoked when the CGColorSpaceRef is itself going away. While objc_setAssociatedObject() does seem to work, the results don't seem deterministic. Is it because objc_setAssociatedObject() simply won't work reliably with CF types?
6
0
619
Aug ’24
include a file with space in its name within xcconfig
Hi, I have a file with a name like this: file name.filetype I need to include it in an xcconfig file. I have read that spaces are used as delimiters in xcconfig files, and I need to correctly quote it. But this is for the framework paths, so not sure if the same applies to config files. This might be a really silly question, but what's the correct quotation format we need to follow? I've tried all the usual stuff: #include "../../../file\ name.filetype" #include "../../../file%20name.filetype" #include "../../../file name.filetype" #include "../../../file"+" "+"name.filetype" But neither is working. Am I having a major brain meltdown moment or is there a specific way to do it? Thanks a lot.
0
0
209
Aug ’24