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

All subtopics

Post

Replies

Boosts

Views

Activity

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
196
Aug ’24
Swift Cocoa: PrintOperation() with Sonoma does not work
I have a Swift Coco program taht print a NSView. It work perfectly fine in Monterey but does show the print panel in Sonoma. I cannot find the problem. Here are the 4 errors: Failed to connect (genericPrinterImage) outlet from (PMPrinterSelectionController) to (NSImageView): missing setter or instance variable Failed to connect (otherPrintersLabel) outlet from (PMPrinterSelectionController) to (NSTextField): missing setter or instance variable Failed to connect (localPrintersLabel) outlet from (PMPrinterSelectionController) to (NSTextField): missing setter or instance variable Failed to connect (genericPrinterImage) outlet from (PMPrinterSelectionController) to (NSImageView): missing setter or instance variable func createPrintOperation() { let printOpts: [NSPrintInfo.AttributeKey: Any] = [ .headerAndFooter: false, .orientation: NSPrintInfo.PaperOrientation.portrait ] let printInfo = NSPrintInfo(dictionary: printOpts) printInfo.leftMargin = 0 printInfo.rightMargin = 0 printInfo.topMargin = 0 printInfo.bottomMargin = 0 printInfo.horizontalPagination = .fit printInfo.verticalPagination = .automatic printInfo.isHorizontallyCentered = true printInfo.isVerticallyCentered = true printInfo.scalingFactor = 1.0 printInfo.paperSize = NSMakeSize(612, 792) // Letter size // Create a print operation with the view you want to print , myPrintView is a NSView let printOperation = NSPrintOperation(view: myPrintView, printInfo: printInfo) // Configure the print panel printOperation.printPanel.options.insert(NSPrintPanel.Options.showsPaperSize) printOperation.printPanel.options.insert(NSPrintPanel.Options.showsOrientation) // Set the job title for the print operation let jobTitle = fact.nom_complet_f.replacingOccurrences(of: " ", with: "") printOperation.jobTitle = jobTitle // Run the print operation printOperation.run() }
2
0
237
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
216
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
178
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
527
Aug ’24
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
413
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
481
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
294
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
358
Aug ’24
StoreKit Promotional Offer Purchase Failure - 'Unable to Purchase' Alert in Xcode
Hi everyone, I'm encountering an issue while testing a subscription purchase with a promotional offer using StoreKit in the Xcode debug environment. I’ve created a subscription in the StoreKit configuration file and added a promotional offer. However, when I attempt to make a purchase with the promotional offer, the process fails, and I receive an alert with the message: "Unable to purchase" "Contact the developer for more information." Here’s the error that is printed in the Xcode logs: Purchase did not return a transaction: Error Domain=ASDErrorDomain Code=3903 "Received failure in response from Xcode" UserInfo={NSDebugDescription=Received failure in response from Xcode, NSUnderlyingError=0x303346b50 {Error Domain=AMSErrorDomain Code=305 "Server Error" UserInfo={NSLocalizedDescription=Server Error, AMSServerErrorCode=3903, AMSServerPayload={ "cancel-purchase-batch" = 1; dialog = { defaultButton = ok; explanation = "Contact the developer for more information.\n\n[Environment: Xcode]"; initialCheckboxValue = 1; "m-allowed" = 0; message = "Unable to Purchase"; okButtonString = OK; }; dsid = 17322632127; failureType = 3903; jingleAction = inAppBuy; jingleDocType = inAppSuccess; pings = ( ); }, AMSURL=http://localhost:49300/WebObjects/MZBuy.woa/wa/inAppBuy, AMSStatusCode=200, NSLocalizedFailureReason=The server encountered an error}}} Has anyone encountered a similar issue, or does anyone have insights into what might be causing this? I’m using StoreKit 2 methods for handling subscriptions, and this error only occurs when attempting to apply the promotional offer. Any help or suggestions would be greatly appreciated! Thanks in advance!
1
0
511
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
280
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
Can't find Python.h anywhere on Mac
I am trying to embed a python file that uses a python library in c, to do this I need to include python.h but I don't see it anywhere on my mac. Right now when I try to compile I just get a missing Python.h compile error. I tried using the search bar to find it in /usr and /library. Neither had the file. I tried doing #include <Python/python.h> and that doesn't change anything. Is trying to setup a virtual env the issue?
2
0
534
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
416
Aug ’24
How to inheritance Cocoapods Library to extend the functionality in the Xcode framework project
When building my iOS framework, I encountered a (fatal) module 'TrustKit' not found issue. I've marked the necessary classes as public (which is inherited from other library classes) for client applications, but I'm unsure how to resolve this error. Example Code Snippet import Foundation import TrustKit @objc public class InheritanceTruskitFrameworkProjectClass: TrustKit { func extraFunctionality() { print("extraFunctionality executing...") } } Error while building the framework in the auto-generated Swift header file (ProjectName-Swift.h) #if !defined(SWIFT_IMPORT_STDLIB_SYMBOL) # define SWIFT_IMPORT_STDLIB_SYMBOL #endif #endif #if defined(__OBJC__) #if __has_feature(objc_modules) #if __has_warning("-Watimport-in-framework-header") #pragma clang diagnostic ignored "-Watimport-in-framework-header" #endif @import Foundation; @import TrustKit; # -> error here `(fatal) module 'TrustKit' not found` #endif #endif #pragma clang diagnostic ignored "-Wproperty-attribute-mismatch" #pragma clang diagnostic ignored "-Wduplicate-method-arg" #if __has_warning("-Wpragma-clang-attribute") # pragma clang diagnostic ignored "-Wpragma-clang-attribute" #endif #pragma clang diagnostic ignored "-Wunknown-pragmas" #pragma clang diagnostic ignored "-Wnullability" #pragma clang diagnostic ignored "-Wdollar-in-identifier-extension" Please check this image to understand the error Sample GitHub project https://github.com/vinaykumar0339/InheritanceTruskitFrameworkProject I want a way to use inheritance for the dependencies project. Is this supported? Looks Like it won't work with any modules like cocopod frameworks, internal module map etc? What I have Tried I have tried to install TrustKit with SPM also the same error throwing (fatal) module 'TrustKit' not found
0
0
370
Aug ’24