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

Device token for DeviceCheck API
Hi all, I'm trying to integrate Apple’s DeviceCheck API into my Flutter iOS app. I already have everything set up on the backend — the Apple private key, key ID, team ID, and DeviceCheck capability. The backend is generating and signing the JWT correctly and making requests to Apple. However, I’m currently stuck on the frontend (Flutter): 👉 How can I generate the device_token required by the DeviceCheck API (via DCDevice.generateToken) in a Flutter iOS app? I understand that DCDevice.generateToken() must be called from native Swift code. I previously attempted to use a MethodChannel to bridge this in Swift, but would prefer not to write or maintain native Swift code if possible. I've looked for a prebuilt Flutter package to handle this, but nothing exists or is up-to-date on pub.dev. Main Question: Is there any Apple-supported way to generate the device_token for DeviceCheck from a Flutter app without writing Swift code manually? If not, is DCDevice.generateToken() the only possible approach, and must I implement this via Swift and Flutter platform channels? Thanks!
0
0
8
3h
UIInputView not being deallocated
I am experiencing memory leaks in my iOS app that seem to be related to an issue between UIInputView and _UIInputViewContent. After using the memory graph, I'm seeing that instances of these objects aren't being deallocated properly. The UIInputViewController whichs holds the inputView is being deallocated properly along with its subviews.I have tried to remove all of UIInputViewController's subviews and their functions but the uiInputView is not being deallocated. The current setup of my app is a collectionView with multiple cell,each possessing a textfield with holds a UIInputViewController.When i scroll up or down,the views are being reused as expected and the number of UIInputViewController stays consistent with the number of textfields.However the number of inputView keeps increasing referencing solely _UIInputViewContent. class KeyboardViewController: UIInputViewController { // Callbacks var key1: ((String) -> Void)? var key2: (() -> Void)? var key3: (() -> Void)? var key4: (() -> Void)? private lazy var buttonTitles = [ ["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"] ] override func viewDidLoad() { super.viewDidLoad() setupKeyboard() } lazy var mainStackView: UIStackView = { let mainStackView = UIStackView() mainStackView.axis = .vertical mainStackView.distribution = .fillEqually mainStackView.spacing = 16 mainStackView.translatesAutoresizingMaskIntoConstraints = false return mainStackView }() private func setupKeyboard() { let keyboardView = UIView(frame:CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 279.0)) keyboardView.addSubview(mainStackView) NSLayoutConstraint.activate([ mainStackView.topAnchor.constraint(equalTo: keyboardView.topAnchor, constant: 16), mainStackView.leadingAnchor.constraint(equalTo: keyboardView.leadingAnchor, constant: 0), mainStackView.trailingAnchor.constraint(equalTo: keyboardView.trailingAnchor, constant: -24), mainStackView.bottomAnchor.constraint(equalTo: keyboardView.bottomAnchor, constant: -35) ]) // Create rows for (_, _) in buttonTitles.enumerated() { let rowStackView = UIStackView() rowStackView.axis = .horizontal rowStackView.distribution = .fillEqually rowStackView.spacing = 1 // Create buttons for each row for title in rowTitles { let button = createButton(title: title) rowStackView.addArrangedSubview(button) } mainStackView.addArrangedSubview(rowStackView) } self.view = keyboardView } private func createButton(title: String) -> UIButton { switch title { ///returns a uibutton based on title } } // MARK: - Button Actions @objc private func numberTapped(_ sender: UIButton) { if let number = sender.title(for: .normal) { key1?(number) } } @objc private func key2Called() { key2?() } @objc private func key3Called() { key3?() } @objc private func key4Called() { key4?() } deinit { // Clear any strong references key1 = nil key2 = nil key3 = nil key4 = nil for subview in mainStackView.arrangedSubviews { if let stackView = subview as? UIStackView { for button in stackView.arrangedSubviews { (button as? UIButton)?.removeTarget(self, action: nil, for: .allEvents) } } } mainStackView.removeFromSuperview() } } Environment iOS 16.3 Xcode 18.3.1 Any insights would be greatly appreciated as this is causing noticeable memory growth in my app over time.
0
0
12
7h
unable to optimize App for iPad
I use swiftui to build apps on iPhone and iPad. There is no problem with the iPhone app. The game display is fully shown on iPhone. However, for the iPad, the game display is not shown and the screen goes black. I had to tap the button on the upper left side.(looks like a side view button) After that, the game display is only shown in the left side in a very small size. How can I make the game display fully shown in the iPad?
0
0
10
2d
NSFileCoordinator Swift Concurrency
I'm working on implementing file moving with NSFileCoordinator. I'm using the slightly newer asynchronous API with the NSFileAccessIntents. My question is, how do I go about notifying the coordinator about the item move? Should I simply create a new instance in the asynchronous block? Or does it need to be the same coordinator instance? let writeQueue = OperationQueue() public func saveAndMove(data: String, to newURL: URL) { let oldURL = presentedItemURL! let sourceIntent = NSFileAccessIntent.writingIntent(with: oldURL, options: .forMoving) let destinationIntent = NSFileAccessIntent.writingIntent(with: newURL, options: .forReplacing) let coordinator = NSFileCoordinator() coordinator.coordinate(with: [sourceIntent, destinationIntent], queue: writeQueue) { error in if let error { return } do { // ERROR: Can't access NSFileCoordinator because it is not Sendable (Swift 6) coordinator.item(at: oldURL, willMoveTo: newURL) try FileManager.default.moveItem(at: oldURL, to: newURL) coordinator.item(at: oldURL, didMoveTo: newURL) } catch { print("Failed to move to \(newURL)") } } }
0
0
16
2d
Getting original LocationNode from hit tested SCNNode
I would like to modify the content of a published LocationNode upon been clicked by the user. But unfortunately: func hitTest(_ point: CGPoint, options: [SCNHitTestOption : Any]? = nil) -> [SCNHitTestResult] returns an SCNNode array from which it is impossible to retrieve the original LocationNode being inserted in order to be able to modify it. Of course the solution would be to either insert the SCNNode corresponding to the inserted LocationNode in a custom class or conversely insert the identifier of the custom object as a tag of the LocationNode, in order to solve the issue. But both options seem impossible to implement. May anyone help me?
1
0
15
2d
Should i set window.isReleasedWhenClosed to true or leave it to default?
Hi, In mac os swift ui application when i set window.isReleasedWhenClosed and when i close the window the app is getting crashed with exc_bad_access. but when i leave it to default value the app is not crashing. for some windows setting window.isReleasedWhenClosed to true is woking properly when closing the windows. But for some windows it is crashing. If i dont set it to true the window is not removed from NSApplication.shared.windows sometimes. I am confused about setting isReleasedWhenClosed to true Could someone calrify on this please. thank in advance.
2
0
26
2d
identifierForVendor Changing Unexpectedly in Some Cases (App Store Builds)
We’ve noticed an unexpected behavior in our production iOS app where the UIDevice.current.identifierForVendor value occasionally changes, even though: The app is distributed via the App Store (not TestFlight or Xcode builds) We do not switch provisioning profiles or developer accounts No App Clips, App Thinning, or other advanced features are in use There’s no manual reinstall or device reset in the scenarios observed (as per user feedback) Any insights or confirmations would be much appreciated. Thanks!
1
0
42
2d
How to retrieve required Apple Pay parameters for PayFort payment request in Swift?
I'm integrating Apple Pay with PayFort in a Swift iOS application, and I’m currently working on preparing a valid purchase request using Apple Pay, as described in PayFort’s documentation: 🔗 https://docsbeta.payfort.com/docs/api/build/index.html?shell#apple-pay-authorization-purchase-request The documentation outlines the following required parameters: apple_data apple_signature apple_header apple_transactionId apple_ephemeralPublicKey apple_publicKeyHash apple_paymentMethod apple_displayName apple_network apple_type Optional: apple_applicationData I understand these should be derived from the PKPayment object after Apple Pay authorization, but I’m having trouble mapping everything correctly. Here’s what I’m seeing in code: payment.token // Returns something like: <PKPaymentToken: 0x28080ae80; transactionIdentifier: "..."; paymentData: 3780 bytes> payment.token.paymentData // Contains 3780 bytes of encrypted data payment.token.paymentData.base64EncodedString() // Returns a long base64 string, which at first glance seems like it could be used for apple_data, // but PayFort doesn't accept it as-is — so this value appears to be incomplete or incorrectly formatted I can successfully retrieve the following values from payment.token.paymentMethod: apple_displayName apple_network apple_type However, I’m still unsure how to extract or build the following in the format accepted by PayFort: apple_data apple_signature apple_header apple_transactionId apple_ephemeralPublicKey apple_publicKeyHash apple_paymentMethod These may be contained within the paymentData JSON, but I’m not sure how to decode it or if Apple allows decrypting it in a way that matches PayFort’s expected format. How can I correctly extract or build apple_data, apple_signature, and apple_header from the Apple Pay token? Also, how should I handle the decryption or decoding (if necessary) of paymentData to retrieve values like apple_transactionId, apple_ephemeralPublicKey, and apple_publicKeyHash? If anyone has successfully set this up or has example code that bridges Apple Pay and PayFort’s expected request format, it would be super helpful! Thanks in advance 🙏
0
0
13
4d
WatchOS Xcode 16.4 to sample live RR intervals from the PPG sensor ERROR
Hi, I am getting an error stating "Argument passed to call that takes no arguments". I want this Apple Watch App to measure and store RR Intervals from the PPG sensor on the Apple Watch for Heart Rate Variability calculations. Please help me fix this, I can't figure it out. Here is my code: heartbeatQuery = HKHeartbeatSeriesQuery(predicate: predicate, dataReceivedHandler: { (query, timeSinceLastBeat, ended, error) in // Switch to main thread for UI updates DispatchQueue.main.async { if let error = error { print("Heartbeat query error: (error.localizedDescription)") self.fetchErrorMessage = "Heartbeat query error: (error.localizedDescription)" // Consider stopping the workout session if the query fails critically // self.stopWorkoutSession() return } if ended { print("Heartbeat query indicates series ended.") } // Append valid RR intervals if timeSinceLastBeat > 0 { self.rrIntervals.append(timeSinceLastBeat) self.beatCount += 1 } } // End DispatchQueue.main.async }) // End query data handler // --- END OF PROBLEMATIC INITIALIZER --- // Execute the query if it was created successfully It recommends the fix as removing this part: '(predicate: predicate, dataReceivedHandler: { (query, timeSinceLastBeat, ended, error) in // Switch to main thread for UI updates DispatchQueue.main.async { if let error = error { print("Heartbeat query error: (error.localizedDescription)") self.fetchErrorMessage = "Heartbeat query error: (error.localizedDescription)" // Consider stopping the workout session if the query fails critically // self.stopWorkoutSession() return } if ended { print("Heartbeat query indicates series ended.") } // Append valid RR intervals if timeSinceLastBeat > 0 { self.rrIntervals.append(timeSinceLastBeat) self.beatCount += 1 } } // End DispatchQueue.main.async })' But after I remove that it says "Cannot assign value of type 'HKHeartbeatSeriesQuery.Type' to type 'HKHeartbeatSeriesQuery'" PLEASE HELP ME Thanks
0
0
21
6d
How to Keep Live Activity in Expanded Dynamic Island State (ActivityKit, iOS 17+)
I'm building a Live Activity using ActivityKit in iOS, and I'm trying to understand how apps like Uber or Lyft manage to keep the Dynamic Island always in its expanded state, without transitioning through the compact phase. In my implementation, the Live Activity always starts in the compact state, and only expands temporarily when I interact with it. I've tried the following: Updating the ContentState frequently using activity.update(using:) I tried updating the activity every 1 second, but it didn’t make a difference. Leaving the compactLeading, compactTrailing, and minimal regions empty using EmptyView() — also didn’t change the behavior. Delaying the initial update by 1 second — no effect. What I'm trying to figure out: Is there any way to programmatically force or request the Dynamic Island to stay in the expanded state? Could this behavior be achieved through push updates, using apns-push-type: liveactivity and a high priority (apns-priority)? What I’m trying to achieve is similar to the behavior shown in the images below — the apps do not transition to the compact island, but instead displays the expanded view immediately. Example:
0
0
30
1w
Issue with calculating the distance between two points on a map
I have an error issue that I haven’t been able to solve despite doing extensive research. In fact the similar examples I have found so far have been educational but I have not been able to make work. The example below I am hoping will be easy to fix as it is only producing errors with one line of code… import SwiftUI import CoreLocation var currentLon = Double() var currentLat = Double() extension CLLocation { class func distance(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) -> CLLocationDistance { let from = CLLocation(latitude: from.latitude, longitude: from.longitude) let to = CLLocation(latitude: to.latitude, longitude: to.longitude) return from.distance(from: to) } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { currentLon = (locations.last?.coordinate.longitude)! currentLat = (locations.last?.coordinate.latitude)! }/*⚠️ Not sure if this function will work? (Update User Location coordinates on the move?)*/ } struct Positions: Identifiable { let id = UUID() let name: String let latitude: Double let longitude: Double var coordinate: CLLocationCoordinate2D { CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } } struct GameMapView: View { let from = CLLocationCoordinate2D(latitude: currentLon, longitude: currentLat) let to = CLLocationCoordinate2D(latitude: thisCardPositionLongitude, longitude: thisCardPositionLongitude) let distanceFrom = from.distance(from: to) /*⚠️ ERRORS: 1. Cannot use instance member 'from' within property initializer; property initializers run before 'self' is available. 2. Cannot use instance member 'to' within property initializer; property initializers run before 'self' is available. 3. Value of type 'CLLocationCoordinate2D' has no member 'distance'. */ @State private var region = MKCoordinateRegion( center: CLLocationCoordinate2D( latitude: thisCardPositionLatitude, longitude: thisCardPositionLongitude), span: MKCoordinateSpan( latitudeDelta: 0.0001, longitudeDelta: 0.0001) ) var body: some View { Map(coordinateRegion: $region, showsUserLocation: true, annotationItems: locations){ place in MapMarker(coordinate: place.coordinate,tint: Color.accentColor) } .edgesIgnoringSafeArea(.all) VStack { Print("Distance from Location: \(distanceFrom)") font(.largeTitle) padding() }
1
0
47
1w
UIDocumentPickerViewController dismisses presenting view controller when selecting a file multiple times quickly
Description When using UIDocumentPickerViewController with allowsMultipleSelection = false, I expect that selecting a file will dismiss only the document picker. However, if a user quickly taps the same file multiple times, the picker dismisses both itself and the presenting view controller (i.e., it pops two levels from the view controller stack), which leads to unintended behavior and breaks presentation flow. Expected Behavior Only UIDocumentPickerViewController should be dismissed when a file is selected—even if the user taps quickly or multiple times on the same file. Actual Behavior When tapping the same file multiple times quickly, the picker dismisses not only itself but also the parent view controller it was presented from. Steps to Reproduce Create a simple view controller and present another one modally over it. From that presented view controller, present a UIDocumentPickerViewController with allowsMultipleSelection = false. Tap quickly on the same file in the picker 2 times. Result: Both the document picker and the presenting view controller are dismissed. Reproducible Code Snippet class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .green addLabel("Parent View Controller") DispatchQueue.main.async { [unowned self] in let child = UIViewController() child.view.backgroundColor = .yellow present(child, animated: true) child.addLabel("Child View Controller") let vc = UIDocumentPickerViewController( forOpeningContentTypes: [.pdf, .jpeg, .png], asCopy: true ) vc.allowsMultipleSelection = false child.present(vc, animated: true) } } } extension UIViewController { func addLabel(_ text: String) { let label = UILabel(frame: CGRect(x: 0, y: 50, width: view.bounds.width, height: 30)) label.text = text view.addSubview(label) } } Environment Device: iPhone 15 Pro and others iOS version: 18.2 (reproduces on multiple iOS versions) Occurs with: .pdf, .jpeg, .png file types Mode: Both simulator and real device Notes Happens consistently with fast multiple taps on the same file. This breaks expected view controller stack behavior.
0
0
23
1w
Crash in Preview (but not in Simulator) when using fileprivate on a protocol in Swift
Consider this stripped-down example of a view with a view model: import Observation import SwiftUI struct MainView: View { @State private var viewModel = ViewModel() private let items = [0, 1, 2] var body: some View { List { GroupedItemsView( viewModel : viewModel.groupState, groupedItems : [(0, items)] ) } } } fileprivate struct GroupedItemsView<ViewModel: GroupsExpandable>: View { let viewModel : ViewModel let groupedItems : [(ViewModel.GroupTag, [Int])] var body: some View { ForEach(groupedItems, id: \.0) { groupTag, items in Text("nothing") } } } fileprivate protocol GroupsExpandable: AnyObject { // HERE associatedtype GroupTag: Hashable } fileprivate final class GroupState<GroupTag: Hashable>: GroupsExpandable {} @Observable fileprivate final class ViewModel { var groupState = GroupState<Int>() } #Preview { MainView() } This compiles and runs fine in the Simulator, but it crashes in the Preview. However, when I remove the fileprivate modifier before GroupsExpandable (see HERE), it also runs in the Preview. What is the reason for this? Bug in Preview? Error on my side somewhere? Thanks. System is Xcode Version 16.3 (16E140) on a MacBook Pro 2018 (Intel) running Sequoia 15.3.2 Devices are iPhone 16 Pro Max with iOS 18.3.1, compiler is set to Swift 6.
1
0
37
1w
Alternate App Icon Change Does Not Reflect in Notification Center on iOS 18.1+
Version: iOS 18.1 and later (works as expected on iOS 18.0 and earlier) Area: SpringBoard / Notification Center / App Icon Rendering Description: When changing the app's alternate icon using UIApplication.setAlternateIconName(_:completionHandler:), the icon is updated correctly on the Home Screen and App Switcher. However, in Notification Center, the old app icon is still shown for notifications, even after the change has completed. This issue only occurs on iOS 18.1 and later. In iOS 18.0 and earlier, Notification Center correctly reflects the updated icon. - Steps to reproduce: Create an iOS app with alternate app icons configured in the Info.plist. Use UIApplication.shared.setAlternateIconName("IconName") to change the icon at runtime. Send a notification. Pull down Notification Center and observe the icon shown beside the notification. - Expected Behavior: Notification Center should reflect the updated (alternate) app icon immediately after the change. - Actual Behavior: Notification Center continues to display the old (primary) app icon. The new icon appears correctly on the Home Screen and App Switcher. Restarting the device does cause Notification Center to update and reflect the correct icon, which suggests a cache or refresh issue in SpringBoard or Notification Center. - Notes: Issue introduced in iOS 18.1; not present in 18.0. Reproduces on both physical devices and simulators. Occurs with both scheduled local notifications and remote notifications. Restarting the device updates the Notification Center icon, but this is not a viable user-facing workaround.
1
0
26
1w
UICollectionView Dequeue Crash Xcode 16.2
I am facing same issue with major crash while coming out from this function. Basically using collectionView.dequeReusableCell with size calculation. func getSizeOfFavouriteCell(_ collectionView: UICollectionView, at indexPath: IndexPath, item: FindCircleInfoCellItem) -> CGSize { guard let dummyCell = collectionView.dequeueReusableCell( withReuseIdentifier: TAButtonAddCollectionViewCell.reuseIdentifier, for: indexPath) as? TAButtonAddCollectionViewCell else { return CGSize.zero } dummyCell.title = item.title dummyCell.subtitle = item.subtitle dummyCell.icon = item.icon dummyCell.layoutIfNeeded() var targetSize = CGSize.zero if viewModel.favoritesDataSource.isEmpty.not, viewModel.favoritesDataSource.count > FindSheetViewControllerConstants.minimumFavoritesToDisplayInSection { targetSize = CGSize(width: collectionView.frame.size.width / 2, height: collectionView.frame.height) var estimatedSize: CGSize = dummyCell.systemLayoutSizeFitting(targetSize) if estimatedSize.width > targetSize.width { estimatedSize.width = targetSize.width } return CGSize(width: estimatedSize.width, height: targetSize.height) } } We have resolve issue with size calculation with checking nil. Working fine in xcode 15 and 16+. Note: Please help me with reason of crash? Is it because of xCode 16.2 onwards **strict check on UICollectionView **
0
0
25
1w
Return the results of a Spotlight query synchronously from a Swift function
How can I return the results of a Spotlight query synchronously from a Swift function? I want to return a [String] that contains the items that match the query, one item per array element. I specifically want to find all data for Spotlight items in the /Applications folder that have a kMDItemAppStoreAdamID (if there is a better predicate than kMDItemAppStoreAdamID > 0, please let me know). The following should be the correct query: let query = NSMetadataQuery() query.predicate = NSPredicate(format: "kMDItemAppStoreAdamID > 0") query.searchScopes = ["/Applications"] I would like to do this for code that can run on macOS 10.13+, which precludes using Swift Concurrency. My project already uses the latest PromiseKit, so I assume that the solution should use that. A bonus solution using Swift Concurrency wouldn't hurt as I will probably switch over sometime in the future, but won't be able to switch soon. I have written code that can retrieve the Spotlight data as the [String], but I don't know how to return it synchronously from a function; whatever I tried, the query hangs, presumably because I've called various run loop functions at the wrong places. In case it matters, the app is a macOS command-line app using Swift 5.7 & Swift Argument Parser 1.5.0. The Spotlight data will be output only as text to stdout & stderr, not to any Apple UI elements.
1
0
23
1w