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

Posts under Swift tag

200 Posts

Post

Replies

Boosts

Views

Activity

Swift Playgrounds Will Not Upload to App Store Connect
When I go to the App Settings menu in Swift Playgrounds and attempt to upload to App Store Connect, I run into the below error screen: I am registered with the Apple Developer Program. Swift Playgrounds is updated to its latest version. This is occurring on both macOS and iPadOS. All the information I put in is valid. Any reason why this would be happening?
2
1
375
Jan ’25
volumeTotalCapacityKey value is lower than total storage in iOS Settings
Hi, I develop a feature to get the iPhone's total storage. After some researching, the way I can get the total storage of iPhone is using this code. class DiskStatus { /// Helper method to query against a resource value key private static func getVolumeResourceValues(for key: URLResourceKey) -> URLResourceValues? { let fileUrl = URL(fileURLWithPath: "/") let results = try? fileUrl.resourceValues(forKeys: [key]) return results } /// Volume’s total capacity in bytes. public static var totalCapacity: Int? { get { let resourceValues = getVolumeResourceValues(for: .volumeTotalCapacityKey) return resourceValues?.volumeTotalCapacity } } } When I print the totalCapacity, its value is 254807724032 bytes. If I convert it to GB using decimal system it will be 254.8GB. When I looked into Settings, the total storage of my iPhone is 256GB. My questions are: Why the total storage shown in Settings different with my code result? How to achieve so that I can show exact value in Settings? Thank you.
1
0
308
Jan ’25
Questions about calculate the square root using Accelerate
I am currently studying the Accelerate library by referring to Apple documentation. Here is the link to the referenced document: https://developer.apple.com/documentation/accelerate/veclib/vforce When I executed the sample code provided at the bottom of the document, I found a case where the results were different. let n = 10_000 let x = (0..<n).map { _ in Float.random(in: 1 ... 10_000) } let y = x.map { return sqrt($0) } and let y = [Float](unsafeUninitializedCapacity: n) { buffer, initializedCount in vForce.sqrt(x, result: &buffer) initializedCount = n } The code below is provided to observe the issue described above. import Accelerate Task { let n = 1//10_000 let x = (0..<n).map { _ in Float(6737.015)//Float.random(in: 1 ... 10_000) } let y = x.map { return sqrt($0) } try? await Task.sleep(nanoseconds: 1_000_000_000) let z = [Float](unsafeUninitializedCapacity: n) { buffer, initializedCount in vForce.sqrt(x, result: &buffer) initializedCount = n } } For a value of 6737.015 when calculating the square root: Using the sqrt(_:) function gives the result 82.07932, While using the vForce.sqrt(_:result:) function gives the result 82.07933. Using a calculator, the value comes out as 82.07932139, which shows that the result from vForce is incorrect. Could you explain the reason behind this difference?
2
0
516
Jan ’25
Regarding the issue of navigation bar hierarchy in iOS 18
I have discovered a strange phenomenon about iOS18.1.1. I set a logo as the titleView in my navigationBar, and then when I added a view to the navigationBar and pushed it to another page before popping it back up, I found that the view hierarchy of the navigationBar would change in a very short time. In this short time, the logo would cover the view. I did not find this phenomenon on devices below iOS18.1.1. I would like to know what changes have occurred in iOS18.1.1 that caused the view hierarchy to change during the pop process. I hope someone can help me. Thank you very much
3
0
647
Jan ’25
Getting precise text position with Swift for MacOS
Hey there! Hope you are starting the year with great joy. My situation I'm building a new product that is based on detecting certain text on screen in realtime. The product is only targeted for Mac and it's built with Swift My problem I need to get the exact position of a text element with the Apple Accessibility API but I can't figurate it out. I managed to get the AXUIElement where the text is placed but it's position is too broad and off target. My discoveries so far I've tried OCR but is too slow for what I'm building, so the only possible way I can think of is with the Accessibility API. Thank you in advanced.
2
0
531
Jan ’25
Need clarification on using Apple MapKit in CarPlay
I have developed a mobile app using SwiftUI that supports GoogleMaps. Now I am in the process of building a CarPlay application. I assume CarPlay only supports Apple MapKit, as I could not find any way to integrate the Google Maps. Below are few queries, Could you please guide me on how I can obtain the user's current location on the CarPlay app launch? Is there a way CarPlay can get the details from the mobile app(not pretty sure as its using Google Maps)? If the user is logged out from the mobile app, what is the flow in CarPlay? Do we have any standard login page asking user to login to the mobile app first? Is there any UI asking the user to capture the location in CarPlay? This is my first CarPlay app. Kindly guide me to a document or so that covers these details. Thanks a ton!!
1
0
448
Jan ’25
*** -colorSpaceName not valid
Here is a relatively simple code fragment: let attributedQuote: [NSAttributedString.Key: Any] = [ .font: FieldFont!, .foregroundColor: NSColor.red] let strQuote = NSAttributedString.init(string:"Hello World", attributes:attributedQuote) strQuote.draw(in: Rect1) It compiles without an issue, bur when I execute it, I get: "*** -colorSpaceName not valid for the NSColor <NSColor: 0x6000005adfd0>; need to first convert colorspace." I have tried everything I can think of. What's going on?
0
1
366
Jan ’25
Swift 6 concurrency error of passing sending closure
I am getting this error in a couple of places in my code with Task closure after setting Swift 6 as Language version in XCode. Passing closure as a 'sending' parameter risks causing data races between code in the current task and concurrent execution of the closure Below is minimally reproducible sample code. import Foundation final class Recorder { var writer = Writer() func startRecording() { Task { await writer.startRecording() print("started recording") } } func stopRecording() { Task { await writer.stopRecording() print("stopped recording") } } } actor Writer { var isRecording = false func startRecording() { isRecording = true } func stopRecording() { isRecording = false } } While making the class Recorder as Actor would fix the problem, I fear I will have to make too many classes as Actors in the class and in my scenario, there could be performance implications where real time audio and video frames are being processed. Further, I don't see any race condition in the code above. Does the error talk about possible race conditions that could arise if I were to call other functions on the self in future, or the current code itself is not safe?
0
2
1.2k
Jan ’25
How to test iPhone app and CarPlay together?
I have developed a mobile app using SwiftUI. Now I am in the process of building a CarPlay application. I know how to test the CarPlay app using a simulator but here is my confusion, How to test the iPhone app and CarPlay together? I want to test few scenarios like, user login / logout from mobile app. Location enabled /disabled in the mobile app. I know that swiftUI handles the scenes by itself. Kindly help me validate the above scenarios as I am getting black screen on iPhone whenever the CarPlay is launched. Below is the code snippet, func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { if connectingSceneSession.role == .carTemplateApplication { let sceneConfiguration = UISceneConfiguration(name: "CarPlay Scene", sessionRole: connectingSceneSession.role) sceneConfiguration.delegateClass = CarPlaySceneDelegate.self return sceneConfiguration } // Configuration for other types of scenes return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } struct MyApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate var body: some Scene { WindowGroup { ContentView() .preferredColorScheme(.light) } } } Info.plist <key>UIApplicationSceneManifest</key> <dict> <key>UIApplicationSupportsMultipleScenes</key> <true/> <key>UISceneConfigurations</key> <dict> <key>CPTemplateApplicationSceneSessionRoleApplication</key> <array> <dict> <key>UISceneConfigurationName</key> <string>CarPlay Scene</string> <key>UISceneDelegateClassName</key> <string>$(PRODUCT_MODULE_NAME).CarPlaySceneDelegate</string> </dict> </array> </dict> </dict>
2
0
596
Jan ’25
ApplicationMusicPlayer stops with error after skipping quickly over playlist entries
ApplicationMusicPlayer with queue created from playlist crashes with random occurrence shortly after skipping back or forth using controls embedded in the notification, with the error on console log: applicationController: xpc service connection interrupted. I've noticed that the issue occurs more frequently the shorter is time between skipping entries. Since ApplicationMusicPlayer is run on a remote process, the main app does not crash, but the music stops playing without any exception, and the playback control turns uninitiated. Here is how I'm initiating the queue: let entries = playlist .with(.entries).entries! .map { ApplicationMusicPlayer.Queue.Entry($0) } ApplicationMusicPlayer.shared.queue = .init( entries, startingAt: entries.last ) Please give me some tips on how to solve this. EDIT: The issue does not occur when navigating quickly through the station.
1
0
491
Jan ’25
WatchConnectivity Swift 6 - Incorrect actor executor assumption
I am trying to migrate a WatchConnectivity App to Swift6 and I found an Issue with my replyHandler callback for sendMessageData. I am wrapping sendMessageData in withCheckedThrowingContinuation, so that I can await the response of the reply. I then update a Main Actor ObservableObject that keeps track of the count of connections that have not replied yet, before returning the data using continuation.resume. ... @preconcurrency import WatchConnectivity actor ConnectivityManager: NSObject, WCSessionDelegate { private var session: WCSession = .default private let connectivityMetaInfoManager: ConnectivityMetaInfoManager ... private func sendMessageData(_ data: Data) async throws -> Data? { Logger.shared.debug("called on Thread \(Thread.current)") await connectivityMetaInfoManager.increaseOpenSendConnectionsCount() return try await withCheckedThrowingContinuation({ continuation in self.session.sendMessageData( data, replyHandler: { data in Task { await self.connectivityMetaInfoManager .decreaseOpenSendConnectionsCount() } continuation.resume(returning: data) }, errorHandler: { (error) in Task { await self.connectivityMetaInfoManager .decreaseOpenSendConnectionsCount() } continuation.resume(throwing: error) } ) }) } Calling sendMessageData somehow causing the app to crash and display the debug message: Incorrect actor executor assumption. The code runs on swift 5 with SWIFT_STRICT_CONCURRENCY = complete. However when I switch to swift 6 the code crashes. I rebuilt a simple version of the App. Adding bit by bit until I was able to cause the crash. See Broken App Awaiting sendMessageData and wrapping it in a task and adding the @Sendable attribute to continuation, solve the crash. See Fixed App But I do not understand why yet. Is this intended behaviour? Should the compiler warn you about this? Is it a WatchConnectivity issue? I initially posted on forums.swift.org, but was told to repost here.
3
0
1.2k
Jan ’25
How to handle a non-consumable in app purchase when SKPaymentQueue is deprecated
I use the code below for a non-consumable in-app purchase in my apps. Has anybody worked out how to handle this without using any of the deprecated items? SKPaymentQueue - deprecated, SKPayment - deprecated, SKProduct - deprecated, transactionState - deprecated, SKPaymentTransaction - deprecated, finishTransaction - deprecated func paymentQueue(_ queue: SKPaymentQueue, shouldAddStorePayment payment: SKPayment, for product: SKProduct) -> Bool { true } func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { for transaction in transactions { switch transaction.transactionState { case .purchasing: break case .purchased: SKPaymentQueue.default().finishTransaction(transaction) // Hide the restore button navigationItem.setRightBarButton(nil, animated: true) // Set the ProVerion in the Db to true IAPHandler.setProVersionToPurchased() // Also hide the Purchase button UIView.animate(withDuration: 1.0, animations: { [weak self] in self?.purchaseBtn_Outlet.alpha = 0 }) { [weak self] (success) in if self!.theDevice.isOneOf(K.Device_Groups.SE_3_iPhone8) { self?.segControlTop_Constraint.constant = 10 } else if self!.theDevice.isPhone { self?.segControlTop_Constraint.constant = 30 } } case .failed: if let error = transaction.error { let errorDescription = error.localizedDescription print("Transaction failed due to error: \(errorDescription)") } case .restored: SKPaymentQueue.default().finishTransaction(transaction) // Hide the restore button navigationItem.setRightBarButton(nil, animated: true) // Set the ProVerion in the Db to true IAPHandler.setProVersionToPurchased() // Also hide the Purchase button UIView.animate(withDuration: 1.0, animations: { [weak self] in self?.purchaseBtn_Outlet.alpha = 0 }) { [weak self] (success) in if self!.theDevice.isOneOf(K.Device_Groups.SE_3_iPhone8) { self?.segControlTop_Constraint.constant = 10 } else if self!.theDevice.isPhone { self?.segControlTop_Constraint.constant = 30 } } case .deferred: break @unknown default: if let error = transaction.error { let errorDescription = error.localizedDescription print("Transaction failed due to error: \(errorDescription)") } break } } } // Sets the purchase to true in the Db class IAPHandler: NSObject { //Get the ProVersion Status static func isProVersionPurchased() -> Bool { let VC_String = "IAPHandler" var theStatus = false do { let settings = try Database.shared.databaseConnection!.read { db in try My_Settings.fetchOne(db) } let theStatusText = settings?.ProVersion ?? "false" theStatus = theStatusText == "true" ? true : false } catch { print("Getting the ProVersion Status failed! \(VC_String) \(error)") } return theStatus } // Set ProVersion to true. static func setProVersionToPurchased() { let VC_String = "IAPHandler" do { try Database.shared.databaseConnection!.write { db in try db.execute(sql: "UPDATE My_Settings SET ProVersion = :proVersion WHERE Settings_ID = :id", arguments: ["proVersion": "true", "id": 1]) } } catch { print("Update set pro version, failed! \(VC_String)s \(error)") } } }// End of class
1
0
339
Jan ’25
DateFormatter return wrong year
my Date type data is "2024-12-28 15:00:00 +0000" and when I use Date formatter to format date with timezone TimeZone(identifier: "Asia/Seoul"), date formatter return wrong year like below (lldb) po print(date); let formatter = DateFormatter(); formatter.timeZone = TimeZone(identifier: "Asia/Seoul"); formatter.dateFormat = "YYYY-MM-dd"; formatter.string(from: date) 2024-12-28 15:00:00 +0000 "2025-12-29" (lldb) po print(date); let formatter = DateFormatter(); formatter.timeZone = .gmt; formatter.dateFormat = "YYYY-MM-dd"; formatter.string(from: date) 2024-12-28 15:00:00 +0000 "2024-12-28"
2
0
548
Jan ’25
Create C++ static library with Swift interoperability for iOS. How?
Hello all! My application written with C++ for iOS. Want to make some functionality in static library for the purpose of reuse it in different C++ projects. Want to make universal library for using StoreKit2. Global idea is to wrap StoreKit2 Swift out with CPP interoperability. Now trying to make clear for my self how to create C++ static library with Swift interoperability for iOS in XCode. There are only Objective-C option when you creating static library in XCode for iOS. Is it correct: Create Static Library with Objective-C in XCode Remove all default Objective-C files Add C++ files Add C++/Swift interoperability in build settings Add swift classes Beside all of it some questions: When C++ static library contain Swift code with interoperability will it require some special settings for project (Swift standard lib or some other settings)? Or it could be used like any other C++ libraries? What is the optimal build settings in this case to reduce dependencies when using it different projects? Is there any examples of the same approach for iOS development?
0
0
365
Jan ’25
Struggling with async/await: Fetching an image off the main thread
Hey everyone, I’m learning async/await and trying to fetch an image from a URL off the main thread to avoid overloading it, while updating the UI afterward. Before starting the fetch, I want to show a loading indicator (UI-related work). I’ve implemented this in two different ways using Task and Task.detached, and I have some doubts: Is using Task { @MainActor the better approach? I added @MainActor because, after await, the resumed execution might not return to the Task's original actor. Is this the right way to ensure UI updates are done safely? Does calling fetchImage() on @MainActor force it to run entirely on the main thread? I used an async data fetch function (not explicitly marked with any actor). If I were to use a completion handler instead, would the function run on the main thread? Is using Task.detached overkill here? I tried Task.detached to ensure the fetch runs on a non-main actor. However, it seems to involve unnecessary actor hopping since I still need to hop back to the main actor for UI updates. Is there any scenario where Task.detached would be a better fit? class ViewController : UIViewController{ override func viewDidLoad() { super.viewDidLoad() //MARK: First approch Task{@MainActor in showLoading() let image = try? await fetchImage() //Will the image fetch happen on main thread? updateImageView(image:image) hideLoading() } //MARK: 2nd approch Task{@MainActor in showLoading() let detachedTask = Task.detached{ try await self.fetchImage() } updateImageView(image:try? await detachedTask.value) hideLoading() } } func fetchImage() async throws -> UIImage { let url = URL(string: "https://via.placeholder.com/600x400.png?text=Example+Image")! //Async data function call let (data, response) = try await URLSession.shared.data(from: url) guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else { throw URLError(.badServerResponse) } guard let image = UIImage(data: data) else { throw URLError(.cannotDecodeContentData) } return image } func showLoading(){ //Show Loader handling } func hideLoading(){ //Hides the loader } func updateImageView(image:UIImage?){ //Image view updated } }
5
0
1.3k
Jan ’25
How to suppress the prohibition mark (🚫) in UITableView drag-and-drop operations?
Question How can I suppress this prohibition mark during this operation? Background I am implementing drag-and-drop functionality in a UITableView to allow users to reorder cells. During the drag operation, when a cell is dragged back to its original position, a prohibition mark (🚫) appears over the cell. I have reviewed the API documentation for UITableViewDragDelegate and UITableViewDropDelegate, but I could not find any clear way to suppress this mark. The behavior does not impact functionality but is visually unappealing. What I Tried Customizing UITableViewDropProposal: I ensured that operation is set to .move and intent to .insertAtDestinationIndexPath. This did not resolve the issue. Customizing drag preview: Using dragPreviewParametersForRowAt to set a clear background. The prohibition mark still appeared. Verifying drop session: Checked the UIDropSession state in dropSessionDidUpdate to ensure valid drop handling. Environment Xcode Version: Version 16.2 Testing Device: iPhone 16 pro + iOS 18.2 Steps to Reproduce Code Example Create new app with this ViewController import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITableViewDragDelegate, UITableViewDropDelegate { let tableView = UITableView() var items = ["Item 1", "Item 2", "Item 3", "Item 4"] override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white tableView.delegate = self tableView.dataSource = self tableView.dragDelegate = self tableView.dropDelegate = self tableView.dragInteractionEnabled = true tableView.translatesAutoresizingMaskIntoConstraints = false tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") tableView.separatorStyle = .none tableView.layer.cornerRadius = 10 tableView.backgroundColor = UIColor.systemGray6 view.addSubview(tableView) NSLayoutConstraint.activate([ tableView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5), tableView.centerXAnchor.constraint(equalTo: view.centerXAnchor), tableView.topAnchor.constraint(equalTo: view.topAnchor, constant: 50), tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -50) ]) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = items[indexPath.row] cell.textLabel?.textAlignment = .center cell.backgroundColor = UIColor.systemBlue.withAlphaComponent(0.2) cell.layer.cornerRadius = 10 cell.clipsToBounds = true return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] { let dragItem = UIDragItem(itemProvider: NSItemProvider(object: items[indexPath.row] as NSString)) dragItem.localObject = items[indexPath.row] return [dragItem] } func tableView(_ tableView: UITableView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UITableViewDropProposal { guard destinationIndexPath != nil else { return UITableViewDropProposal(operation: .cancel) } return UITableViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath) } func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) { guard let destinationIndexPath = coordinator.destinationIndexPath, let dragItem = coordinator.items.first?.dragItem.localObject as? String else { return } if let sourceIndex = items.firstIndex(of: dragItem) { tableView.performBatchUpdates { items.remove(at: sourceIndex) items.insert(dragItem, at: destinationIndexPath.row) tableView.moveRow(at: IndexPath(row: sourceIndex, section: 0), to: destinationIndexPath) } coordinator.drop(coordinator.items.first!.dragItem, toRowAt: destinationIndexPath) } } } Run simulator and start dragging a cell without moving it to a different position. Observe that a prohibition mark appears at the upper right of the cell Any guidance would be greatly appreciated. Thank you in advance!
1
0
352
Jan ’25
Reusing string catalog translations in swift packages
Setup I have 2 swift packages and I try to use stirng catalog to manage your localizations I would like to use some specific keys in these packages and some common ones (e.g. "ok_button_tittle") Problem statement I really don't like the idea of creating separate (but the same) translations in these packages I have tried using something like String( localized: "ok_button_title", table: "Localizable", bundle: .main, comment: "Ok button title" ) This does use translations from the main bundle, however this does not automatically create the keys in string catalog Question Is there any possibility to reuse the translations from the main bundle? Maybe there is a hack to make the keys appear automatically in the correct bundle? Or is it a bug?
1
0
454
Jan ’25
What is ImmersiveSpaceAppModel in BOT-anist?
I would like to implement an expression that pops out from the window to Immersive based on the following WWDC video. This video introduces the new features of visionOS 2.0 in the form of refurbishing Apple's sample app BOT-anist. https://developer.apple.com/jp/videos/play/wwdc2024/10153/?time=1252 In the video, it looks like ImmersiveSpaceAppModel is newly implemented. However, the key code is not mentioned anywhere. You pass appModel.robot as the from argument to the transform method of RealityViewContent. It seems that BOT-anist has been updated once and can be downloaded from the following URL, but there is no class such as ImmersiveSpaceAppModel implemented in this app either. https://developer.apple.com/documentation/visionos/bot-anist Has it been further updated again? Frankly, I'm not sure if it is possible to proceed as per the WWDC video. Translated with DeepL.com (free version)
1
0
438
Jan ’25