Swift is a powerful and intuitive programming language for Apple platforms and beyond.

Posts under Swift tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Coverting CVPixelBuffer 2VUY to a Metal Texture
I am working on a project for macOS where I am taking an AVCaptureSession's CVPixelBuffer and I need to convert it into a MTLTexture for rendering. On macOS the pixel format is 2vuy, there does not seem to be a clear format conversion while converting to a metal texture. I have been able to convert it to a texture but the color space seems to be off as it is rendering distorted colors with a double image. I believe 2vuy is a single pane color space and I have tried to account for that, but I am unaware of what is off. I have attached The CVPixelBuffer and The distorted MTLTexture along with a laundry list of errors. On iOS my conversions are fine, it is only the macOS 2vuy pixel format that seems to have issues. My code for the conversion is also attached. If there are any suggestions or guidance on how to properly convert a 2vuy CVPixelBuffer to a MTLTexture I would greatly appreciate it. Many Thanks Conversion_Logs.txt ConversionCode.swift
0
0
16
1h
Coverting CVPixelBuffer 2VUY to a Metal Texture
I am working on a project for macOS where I am taking an AVCaptureSession's CVPixelBuffer and I need to convert it into a MTLTexture for rendering. On macOS the pixel format is 2vuy, there does not seem to be a clear format conversion while converting to a metal texture. I have been able to convert it to a texture but the color space seems to be off as it is rendering distorted colors with a double image. I believe 2vuy is a single pane color space and I have tried to account for that, but I am unaware of what is off. I have attached The CVPixelBuffer and The distorted MTLTexture along with a laundry list of errors. On iOS my conversions are fine, it is only the macOS 2vuy pixel format that seems to have issues. My code for the conversion is also attached. If there are any suggestions or guidance on how to properly convert a 2vuy CVPixelBuffer to a MTLTexture I would greatly appreciate it. Many Thanks Conversion_Logs.txt ConversionCode.swift
0
0
10
1h
Incoming call notifications problems
Good day We developed a simple swift code to make the device ringing when a certain type of notifications arrives from our backend. This is the code: let phoneNumber = CXHandle(type: .generic, value: (self.userInfoForPluginCall!["data"] as! [String:Any]) ["caller"] as! String) callUpdate.remoteHandle = phoneNumber let configuration = CXProviderConfiguration(localizedName: "Trec Conf") configuration.maximumCallGroups = 1 configuration.maximumCallsPerCallGroup = 1 configuration.supportsVideo = false configuration.supportedHandleTypes = [.generic] configuration.iconTemplateImageData = UIImage(named: "callkit-icon")?.pngData() let callProvider = CXProvider(configuration: configuration) callProvider.setDelegate(self, queue: nil) callProvider.reportNewIncomingCall(with: callUUID!, update: callUpdate, completion: {error in}) We are noticing some problems on the call screen: on certain devices (iOS 18.4RC) the normal call screen appears and the user can answer or decline the call, on other devices (iOS 18.3, especially with dynamic island) only a phone icon appears in the upper right corner and no possibility to answer or deny call. Any idea on why we are encountering that behavior? Thanks
0
0
34
2d
Integrating binary inside Framework via SPM
So I will summary an issue one of our clients has asked us on GitHub: https://github.com/pendo-io/pendo-mobile-sdk/issues/233 Project that is a custom framework that uses different SPM packages (one of them is Binary package), we have our main logic inside that framework and we have different targets that use this framework, everything works on the simulator, but running the app on the actual device provokes a crash saying "Binary framework was not found". We have like 20 other SPM packages that work fine, this is the first one we have an issue with. Please note I understand that SPM will not copy paste the Binary for the magic framework as it does for the apps so I suggested to embed it manually. So my question is what the best(easy) way to do it. Please refer to the following issue for more details: https://github.com/pendo-io/pendo-mobile-sdk/issues/233
0
0
19
2d
tableView.dequeueReusableHeaderFooterView(withIdentifier: ) crashes on iPad only
I have created a custom class: class TarifsHeaderFooterView: UITableViewHeaderFooterView { …} With its init: override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) configureContents() } I register the custom header view in viewDidLoad of the class using the tableView. Table delegate and data source are defined in storyboard. tarifsTableView.register(TarifsHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: headerTarifsIdentifier) And call it: func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerTarifsIdentifier) as! TarifsHeaderFooterView That works on iPhone (simulators and devices). But it crashes on any iPad simulator, as tableView.dequeueReusableHeaderFooterView(withIdentifier: headerTarifsIdentifier) is found nil. What difference between iPhone and iPad do I miss that explains this crash ? PS: sorry for the messy message. It looks like the new "feature" of the forum to put a Copy code button on the code parts, causes the code sections to be put at the very end of the post, not at the place they should be.
1
0
32
2d
How to programmatically set cursor position of a text field in SwiftUI
I would like to understand how to programmatically set the position of a cursor in a SwiftUI TextField. In UIKit this can be done using the selectedTextRange property, but I couldn't find a similar way to achieve this with pure SwiftUI. I want to figure out something like setCursorPosition (index:) - maybe by tracking the position in a @State or any other way. I understand that I can do this using UIViewRepresentable but I am looking for a pure SwiftUI solution and wanted to know if there is any.
1
0
21
1d
Spotlight search by keywords setuped in NSUserActivity doesn't work
Hey there! I faced issue in iOS 18 and newer when Spotlight search doesn't show my App in results. In older versions it works. Here is my code: func configureUserActivitity(with id: String, keywords: [String]) { let activity = NSUserActivity(activityType: id) activity.contentAttributeSet = self.defaultAttributeSet activity.isEligibleForSearch = true activity.keywords = Set(keywords) activity.becomeCurrent() self.userActivity = activity } I didn't find any reasons why it doesn't work now. Maybe I should report a bug?
5
0
55
1d
How to determine which ui control is found first in the view hierarchy, when I assign the same keyboardShortcut () to 2 buttons?
import SwiftUI struct ContentView: View { var body: some View { VStack { Button ("Button 1") { print ("Button 1"); } .keyboardShortcut("k", modifiers: .command) Button ("Button 2") { print ("Button 2"); } .keyboardShortcut("k", modifiers: .command) } } } I the above snippet, I have assigned the same keyboard shortcut (cmd +k) to 2 different buttons. According to the docs, if multiple controls are associated with the same shortcut, the first one found is used. How do I figure out if Button 1 would be found first during the traversal or Button 2 ? Is it based on the order of declaration? Is it always the case that Button 1 would be found first since it was declared before Button 2 ?
0
0
16
2d
How to implement a CoreML model into an iOS app properly?
I am working on a lung cancer scanning app in for iOS with a CoreML model and when I test my app on a physical device, the model results in the same prediction 100% of the time. I even changed the names around and still resulted in the same case. I have listed my labels in cases and when its just stuck on the same case (case 1) My code is below: https://github.com/ShivenKhurana1/Detect-to-Protect-App/blob/main/DetectToProtect/SecondView.swift I couldn't add the code as it was too long so I hope github link is fine!
1
0
28
1d
setCodeSigningRequirement seems not to work in new Service Management API setup.
I have developed a sample app following the example found Updating your app package installer to use the new Service Management API and referring this discussion on XPC Security. The app is working fine, I have used Swift NSXPCConnection in favour of xpc_connection_create_mach_service used in the example. (I am running app directly from Xcode) I am trying to set up security requirements for the client connection using setCodeSigningRequirement on the connection instance. But it fails for even basic requirement connection.setCodeSigningRequirement("anchor apple"). Error is as follows. cannot open file at line 46986 of [554764a6e7] os_unix.c:46986: (0) open(/private/var/db/DetachedSignatures) - Undefined error: 0 xpc_support_check_token: anchor apple error: Error Domain=NSOSStatusErrorDomain Code=-67050 "(null)" status: -67050 I have used codesign -d --verbose=4 /path/to/executable to check the attributes I do get them in the terminal. Other way round, I have tried XPC service provider sending back process id (pid) with each request, and I am probing this id to get attributes using this code which gives all the details. func inspectCodeSignature(ofPIDString pidString: String) { guard let pid = pid_t(pidString) else { print("Invalid PID string: \(pidString)") return } let attributes = [kSecGuestAttributePid: pid] as CFDictionary var codeRef: SecCode? let status = SecCodeCopyGuestWithAttributes(nil, attributes, [], &codeRef) guard status == errSecSuccess, let code = codeRef else { print("Failed to get SecCode for PID \(pid) (status: \(status))") return } var staticCode: SecStaticCode? let staticStatus = SecCodeCopyStaticCode(code, [], &staticCode) guard staticStatus == errSecSuccess, let staticCodeRef = staticCode else { print("Failed to get SecStaticCode (status: \(staticStatus))") return } var infoDict: CFDictionary? if SecCodeCopySigningInformation(staticCodeRef, SecCSFlags(rawValue: kSecCSSigningInformation), &infoDict) == errSecSuccess, let info = infoDict as? [String: Any] { print("🔍 Code Signing Info for PID \(pid):") print("• Identifier: \(info["identifier"] ?? "N/A")") print("• Team ID: \(info["teamid"] ?? "N/A")") if let entitlements = info["entitlements-dict"] as? [String: Any] { print("• Entitlements:") for (key, value) in entitlements { print(" - \(key): \(value)") } } } else { print("Failed to retrieve signing information.") } var requirement: SecRequirement? if SecRequirementCreateWithString("anchor apple" as CFString, [], &requirement) == errSecSuccess, let req = requirement { let result = SecStaticCodeCheckValidity(staticCodeRef, [], req) if result == errSecSuccess { print("Signature is trusted (anchor apple)") } else { print("Signature is NOT trusted by Apple (failed anchor check)") } } var infoDict1: CFDictionary? let signingStatus = SecCodeCopySigningInformation(staticCodeRef, SecCSFlags(rawValue: kSecCSSigningInformation), &infoDict1) guard signingStatus == errSecSuccess, let info = infoDict1 as? [String: Any] else { print("Failed to retrieve signing information.") return } print("🔍 Signing Info for PID \(pid):") for (key, value) in info.sorted(by: { $0.key < $1.key }) { print("• \(key): \(value)") } } If connection.setCodeSigningRequirement does not works I plan to use above logic as backup. Q: Please advise is there some setting required to be enabled or I have to sign code with some flags enabled. Note: My app is not running in a Sandbox or Hardened Runtime, which I want.
4
0
57
1d
@Query with Set
How do I filter data using @Query with a Set of DateComponents? I successfully saved multiple dates using a MultiDatePicker in AddView.swift. In ListView.swift, I want to retrieve all records for the current or today’s date. There are hundreds of examples using @Query with strings and dates, but I haven’t found an example of @Query using a Set of DateComponents Nothing will compile and after hundreds and hundreds of attempts, my hair is turning gray. Please, please, please help me. For example, if the current date is Tuesday, March 4 205, then I want to retrieve both records. Since both records contain Tuesday, March 4, then retrieve both records. Sorting works fine because the order by clause uses period which is a Double. Unfortunately, my syntax is incorrect and I don’t know the correct predicate syntax for @Query and a Set of DateComponents. Class Planner.swift file import SwiftUI import SwiftData 
 @Model class Planner { //var id: UUID = UUID() var grade: Double = 4.0 var kumi: Double = 4.0 var period: Double = 1.0 var dates: Set<DateComponents> = [] init( grade: Double = 4.0, kumi: Double = 4.0, period: Double = 1.0, dates: Set<DateComponents> = [] ) { self.grade = grade self.kumi = kumi self.period = period self.dates = dates 
 } } @Query Model snippet of code does not work The compile error is to use a Set of DateComponents, not just DateComponents. @Query(filter: #Predicate<Planner> { $0.dates = DateComponents(calendar: Calendar.current, year: 2025, month: 3, day: 4)}, sort: [SortDescriptor(\Planner.period)]) var planner: [Planner] ListView.swift image EditView.swift for record #1 DB Browser for SQLlite: record #1 (March 6, 2025 and March 4, 2025) 
 
 [{"isLeapMonth":false,"year":2025,"day":6,"month":3,"calendar":{"identifier":"gregorian","minimumDaysInFirstWeek":1,"current":1,"locale":{"identifier":"en_JP","current":1},"firstWeekday":1,"timeZone":{"identifier":"Asia\/Tokyo"}},"era":1},{"month":3,"year":2025,"day":4,"isLeapMonth":false,"era":1,"calendar":{"locale":{"identifier":"en_JP","current":1},"timeZone":{"identifier":"Asia\/Tokyo"},"current":1,"identifier":"gregorian","firstWeekday":1,"minimumDaysInFirstWeek":1}}]
 EditView.swift for record #2 DB Browser for SQLlite: record #2 (March 3, 2025 and March 4, 2025) 
 [{"calendar":{"minimumDaysInFirstWeek":1,"locale":{"current":1,"identifier":"en_JP"},"timeZone":{"identifier":"Asia\/Tokyo"},"firstWeekday":1,"current":1,"identifier":"gregorian"},"month":3,"day":3,"isLeapMonth":false,"year":2025,"era":1},{"year":2025,"month":3,"era":1,"day":4,"isLeapMonth":false,"calendar":{"identifier":"gregorian","current":1,"firstWeekday":1,"minimumDaysInFirstWeek":1,"timeZone":{"identifier":"Asia\/Tokyo"},"locale":{"current":1,"identifier":"en_JP"}}}]
 
 Any help is greatly appreciated.
1
0
32
3d
Named Entity Recognition Model for Measurements
In an under-development MacOS & iOS app, I need to identify various measurements from OCR'ed text: length, weight, counts per inch, area, percentage. The unit type (e.g. UnitLength) needs to be identified as well as the measurement's unit (e.g. .inches) in order to convert the measurement to the app's internal standard (e.g. centimetres), the value of which is stored the relevant CoreData entity. The use of NLTagger and NLTokenizer is problematic because of the various representations of the measurements: e.g. "50g.", "50 g", "50 grams", "1 3/4 oz." Currently, I use a bespoke algorithm based on String contains and step-wise evaluation of characters, which is reasonably accurate but requires frequent updating as further representations are detected. I'm aware of the Python SpaCy model being capable of NER Measurement recognition, but am reluctant to incorporate a Python-based solution into a production app. (ref [https://developer.apple.com/forums/thread/30092]) My preference is for an open-source NER Measurement model that can be used as, or converted to, some form of a Swift compatible Machine Learning model. Does anyone know of such a model?
0
0
33
6d
The iPad software keyboard becomes impossible to show programmatically when an external keyboard is connected.
When an external keyboard is connected to the iPad, the software keyboard often becomes hidden and cannot be made to show again programmatically. Help! Is there a way to programmatically get the software keyboard to re-appear when an external keyboard is connected without clicking 'Show Keyboard' from the Keyboard Shortcuts menu-item button? Its corner-casey for sure, (with our own keyboard extension) we have a sub-view that is added to the software keyboard view under a certain use case. When the user has an external keyboard connected, everything is fine until the app is backgrounded. When the app is re-foregrounded the software keyboard often becomes hidden (what the user now sees is a keyboard shortcut menu-item group w/a keyboard button and a mic button.) This makes it impossible for the user to interact with the subview we added (because it is hidden), unless the user manually shows the software keyboard again by clicking "Show Keyboard" from the keyboard shortcut. The software keyboard view is still the 'firstResponder' (accepting key strokes, etc), we just cannot find a way to programmatically make it visible again. Sigh.
1
0
45
14h
Get NFC Data Identity card
Hello, I have to create an app in Swift that it scan NFC Identity card. It extract data and convert it to human readable data. I do it with below code import CoreNFC class NFCIdentityCardReader: NSObject , NFCTagReaderSessionDelegate { func tagReaderSessionDidBecomeActive(_ session: NFCTagReaderSession) { print("\(session.description)") } func tagReaderSession(_ session: NFCTagReaderSession, didInvalidateWithError error: any Error) { print("NFC Error: \(error.localizedDescription)") } var session: NFCTagReaderSession? func beginScanning() { guard NFCTagReaderSession.readingAvailable else { print("NFC is not supported on this device") return } session = NFCTagReaderSession(pollingOption: .iso14443, delegate: self, queue: nil) session?.alertMessage = "Hold your NFC identity card near the device." session?.begin() } func tagReaderSession(_ session: NFCTagReaderSession, didDetect tags: [NFCTag]) { guard let tag = tags.first else { session.invalidate(errorMessage: "No tag detected") return } session.connect(to: tag) { (error) in if let error = error { session.invalidate(errorMessage: "Connection error: \(error.localizedDescription)") return } switch tag { case .miFare(let miFareTag): self.readMiFareTag(miFareTag, session: session) case .iso7816(let iso7816Tag): self.readISO7816Tag(iso7816Tag, session: session) case .iso15693, .feliCa: session.invalidate(errorMessage: "Unsupported tag type") @unknown default: session.invalidate(errorMessage: "Unknown tag type") } } } private func readMiFareTag(_ tag: NFCMiFareTag, session: NFCTagReaderSession) { // Read from MiFare card, assuming it's formatted as an identity card let command: [UInt8] = [0x30, 0x04] // Example: Read command for block 4 let requestData = Data(command) tag.sendMiFareCommand(commandPacket: requestData) { (response, error) in if let error = error { session.invalidate(errorMessage: "Error reading MiFare: \(error.localizedDescription)") return } let readableData = String(data: response, encoding: .utf8) ?? response.map { String(format: "%02X", $0) }.joined() session.alertMessage = "ID Card Data: \(readableData)" session.invalidate() } } private func readISO7816Tag(_ tag: NFCISO7816Tag, session: NFCTagReaderSession) { let selectAppCommand = NFCISO7816APDU(instructionClass: 0x00, instructionCode: 0xA4, p1Parameter: 0x04, p2Parameter: 0x00, data: Data([0xA0, 0x00, 0x00, 0x02, 0x47, 0x10, 0x01]), expectedResponseLength: -1) tag.sendCommand(apdu: selectAppCommand) { (response, sw1, sw2, error) in if let error = error { session.invalidate(errorMessage: "Error reading ISO7816: \(error.localizedDescription)") return } let readableData = response.map { String(format: "%02X", $0) }.joined() session.alertMessage = "ID Card Data: \(readableData)" session.invalidate() } } } But I got null. I think that these data are encrypted. How can I convert them to readable data without MRZ, is it possible ? I need to get personal informations from Identity card via Core NFC. Thanks in advance. Best regards
0
0
37
1w
getDeliveredNotifications does not return notifications triggered by UNLocationNotificationTrigger
I am trying to retrieve delivered notifications using UNUserNotificationCenter.getDeliveredNotifications(completionHandler:), but I have encountered an issue: Notifications triggered by UNTimeIntervalNotificationTrigger or UNCalendarNotificationTrigger appear in the delivered list. However, notifications triggered by UNLocationNotificationTrigger do not appear in the list. Here is the code I use to fetch delivered notifications: UNUserNotificationCenter.current().getDeliveredNotifications { notifications in for notification in notifications { print("Received notification: \(notification.request.identifier)") } } The notification is scheduled as follows: let center = UNUserNotificationCenter.current() let content = UNMutableNotificationContent() content.title = "Test Notification" content.body = "This is a location-based notification." content.sound = .default let coordinate = CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194) // Example coordinates let region = CLCircularRegion(center: coordinate, radius: 100, identifier: "TestRegion") region.notifyOnEntry = true region.notifyOnExit = false let trigger = UNLocationNotificationTrigger(region: region, repeats: false) let request = UNNotificationRequest(identifier: "LocationTest", content: content, trigger: trigger) center.add(request) { error in if let error = error { print("Error adding notification: \(error.localizedDescription)") } } Why does getDeliveredNotifications not return notifications that were triggered using UNLocationNotificationTrigger? How can I retrieve such notifications after they have been delivered?
1
0
44
6d
CoreBluetooth and Swift strict concurrency checking
As of iOS 18.3 SDK, Core Bluetooth is still mostly an Objective-C framework: key objects like CBPeripheral inherit from NSObjectProtocol and does not conform to Sendable. CBCentralManager has a convenience initializer that allows the caller to provide a dispatch_queue for delegate callbacks. I want my Swift package that implements Core Bluetooth to conform to Swift 6 strict concurrency checking. It is unsafe to dispatch the delegate events onto my own actor, as the passed in objects are presumably not thread-safe. What is the recommended concurrency safe way to implement Core Bluetooth in Swift 6 with strict concurrency checking enabled?
0
0
57
1w
Issue with record.changePassword Clearing Keychain Information Hello,
I am developing a sample authorization plugin to sync the user’s local password to the network password. During the process, I prompt the user to enter both their old and new passwords in custom plugin. After the user enters the information, I use the following code to sync the passwords: try record.changePassword(oldPssword, toPassword: newPassword) However, I have noticed that this is clearing all saved keychain information, such as web passwords and certificates. Is it expected behavior for record.changePassword to clear previously stored keychain data? If so, how can I overcome this issue and ensure the keychain information is preserved while syncing the password? Thank you for your help!
1
0
36
1w
NSString initWithFormat crash on ios18
var format = "%7B%22sign%22%3Anull%2C%22company%22%3A%22%E5%85%84%E5%BC%9F%E6%B5%B7%E6%B4%8B%E7%A7%91%E6%8A%80%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8%22%2C%22businessNo%22%3Anull%2C%22scene%22%3Anull%2C%22interviewCode%22%3A%22767676%22%7D" let message = withVaList([]) { args in let msg = NSString(format: format, arguments: args) print(msg) }
6
0
79
4d