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

StoreKit 2 - "Storefront Not Available" on TestFlight (Works on Simulator)
I'm having issues with StoreKit 2 when trying to load my auto-renewable subscriptions on a physical device via TestFlight. It works perfectly in the simulator using a local .storekit configuration file, but when I install the app through TestFlight, StoreKit does not return any products at all. Instead, I get the error: "Storefront not available" What I've Tried: ✅ In-App Purchases are enabled on my device. ✅ Using a sandbox account (confirmed logged in under Settings > Developer > Sandbox Account). ✅ The app is signed correctly with automatic signing in Xcode. ✅ The product IDs are correct (they work in the simulator with the local StoreKit file). ✅ I enabled SK2DebugLogging, but I don't see detailed errors. ✅ Restarted the device and signed out/in of my sandbox account. ✅ Checked that the App Store region matches my sandbox account’s region. ✅ The app is not fetching products dynamically at all on a real device—just getting "storefront not available." Additional Notes The app is installed via TestFlight, not running in debug mode from Xcode. The app is signed in to the App Store with a real Apple ID (not the sandbox one). Apple confirmed that products don’t need to be "Ready for Sale" for sandbox testing. I checked the Console.app logs on my Mac, but nothing obvious showed up. What I Need Help With Why would StoreKit 2 fail to return products in TestFlight, but work fine in the simulator? What does "storefront not available" actually mean in this context? Any steps I might have missed to force StoreKit to fetch products properly? Any help would be greatly appreciated! 🚀
1
0
75
Apr ’25
Versioning Question
I created a build and in the info.plist "Bundle version string (short)" is set to "$(MARKETING_VERSION)". In the project settings the marketing version is set 5.0 and this shows in Testfight. When I submitted the app for review I set the app store version number to 3.3. I know the app will appear in the appstore as v3.3. Before I release this app I need to know: What number will be returned by "infoDictionary?["CFBundleShortVersionString"]"? 5.0 or 3.3?
2
0
62
Mar ’25
Can We Detect When Running Behind a Slide Over Window?
I'm trying to determine if it’s possible to detect when a user interacts with a Slide Over window while my app is running in the background on iPadOS. I've explored lifecycle methods such as scenePhase and various UIApplication notifications (e.g., willResignActiveNotification) to detect focus loss, but these approaches don't seem to capture the event reliably. Has anyone found an alternative solution or workaround for detecting this specific state change? Any insights or recommended practices would be greatly appreciated.
0
0
53
Mar ’25
SwiftData Lightweight Migraton failed with VersionedSchema
Setup I am running a versionedSchema for my SwiftData model and attempting a migration. The new version contains a new attribute, with a type of a new custom enum defined in the @Model class, a default value, and a private(set). Migration was completed with a migrationPlan with nil values for willMigrate and didMigrate. Example - Previous Version @Model class MyNumber { var num: Int init() { // Init Code } } Example - Newest Version @Model class MyNumber { var num: Int private(set) var rounding: RoundAmount = MyNumber.RoundAmount.thirtyMinute init() { // Init Code } enum RoundAmount { case fiveMinute, tenMinute, thirtyMinute } } Issue Running this code, I get a swiftData error for “SwiftData/ModelCoders.swift:1585: nil value passed for a non-optional keyPath, /MyNumber.rounding” I assume this means a failure of the swiftData lightweight migration? I have reverted the version, removed private(set) and re-tried the migration with no success. Using the versionedSchema with migrationPlans, are lightweight migrations possible? Could this be an issue with the use of a custom enum? Other changes in my actual project migrated successfully so I’m lost on why I’m having this issue.
1
0
78
Apr ’25
scenePhase not behaving as expected on screen lock
Seeing weird sequences of changes when locking the screen when view is visable. .onChange(of: scenePhase) { phase in if phase == .active { if UIApplication.shared.applicationState == .active { print("KDEBUG: App genuinely became active") } else { print("KDEBUG: False active signal detected") } } else if phase == .inactive { print("KDEBUG: App became inactive") // Handle inactive state if needed } else if phase == .background { print("KDEBUG: App went to background") // Handle background state if needed } } seen: (locks screen) KDEBUG: App became inactive KDEBUG: App genuinely became active KDEBUG: App went to background expected (locks screen) KDEBUG: App became inactive KDEBUG: App went to background
2
0
70
Apr ’25
Why does Array's contains(_:) method cause an error when comparing an optional value with a non-optional value in Swift?
I’m working with Swift and encountered an issue when using the contains method on an array. The following code works fine: let result = ["hello", "world"].contains(Optional("hello")) // ✅ Works fine However, when I try to use the same contains method with the array declared in a separate constant(or variable), I get a compile-time error: let stringArray = ["hello", "world"] let result = stringArray.contains(Optional("hello")) // ❌ Compile-time error The compiler produces the following error message: Cannot convert value of type 'Optional<String>' to expected argument type 'String' Both examples seem conceptually similar, but the second one causes a compile-time error, while the first one works fine. This confuses me because I know that Swift automatically promotes a non-optional value to an optional when comparing it with an optional value. This means "hello" should be implicitly converted to Optional("hello") for the comparison. What I understand so far: The contains(_:) method is defined as: func contains(_ element: Element) -> Bool Internally, it calls contains(where:), as seen in the Swift source code: 🔗 Reference contains(where:) takes a closure that applies the == operator for comparison. Since Swift allows comparing String and String? directly (String is implicitly promoted to String? when compared with an optional), I expected contains(where:) to work the same way. My Questions: Why does the first example work, but the second one fails with a compile-time error? What exactly causes this error in the second case, even though both cases involve comparing an optional value with a non-optional value? Does contains(_:) behave differently when used with an explicit array variable rather than a direct array literal? If so, why? I know that there are different ways to resolve this, like using nil coalescing or optional binding, but what I’m really looking for is a detailed explanation of why this issue occurs at the compile-time level. Can anyone explain the underlying reason for this behavior?
3
0
98
Mar ’25
Why does Array.contains cause a compile-time error when comparing an optional value with a non-optional value in Swift?
I’m working with Swift and ran into an issue when using the contains(_:) method on an array. The following code works fine: let result = ["hello", "world"].contains(Optional("hello")) // ✅ Works fine But when I try to use the same contains method with the array declared in a separate variable, I get a compile-time error: let stringArray = ["hello", "world"] let result = stringArray.contains(Optional("hello")) // ❌ Compile-time error Both examples seem conceptually similar, but the second one causes a compile-time error, while the first one works fine. I understand that when comparing an optional value (Optional("hello")) with a non-optional value ("hello"), Swift automatically promotes the non-optional value to an optional (i.e., "hello" becomes Optional("hello")). 🔗 reference What I don’t understand is why the first code works but the second one doesn’t, even though both cases involve comparing an optional value with a non-optional value. I know that there are different ways to resolve this, like using nil coalescing or optional binding, but what I’m really looking for is a detailed explanation of why this issue occurs at the compile-time level. Can anyone explain the underlying reason for this behavior?
1
0
63
Mar ’25
.onAppear and .task code not running
Hi, I have the following code, which for some reason is not working as expected. I have an .onAppear and a .task function that isn't running, which I can see isn't running because nothing is printing. Any guidance would be greatly appreciated. Thank you. struct ContentView: View { var body: some View { ZStack { switch view { case .view1: View1() case .view2: View2() case .view3: View3() case .view4: View4() case .view5: View5() default: SubscriptionStoreView(groupID: "") } } .onAppear() { view = .view6 print("test 1") } .task { print("test") await refreshPurchasedProducts() } } func refreshPurchasedProducts() async { // Iterate through the user's purchased products. for await verificationResult in Transaction.currentEntitlements { switch verificationResult { case .verified(let transaction): print("verified") case .unverified(let unverifiedTransaction, let verificationError): print("unverified") default: print("default") } } } }
Topic: Design SubTopic: General Tags:
6
0
122
Apr ’25
Active Compilation Conditions in Packages
The flags like #if DEBUG ... endif are dependent on the Active Compilation Conditions. So if they say DEBUG the enclosed code block will be executed, otherwise not. Now I have the phenomenon that a #DEBUG block in a Package does not evaluate these conditions. It rather depends on the name of the configuration used to build. So if I build my app with Active Compilation Condition set to DEBUG, but the configuration name is something like App-Release, the DEBUG block in my Package is not added/executed. The ones which are directly in the project are added. Vice versa if the Compilation Condition say RELEASE but the configuration is called App-Debug the blocks in the Package are added to the compilation, but the ones in the project itself are not It suffices that the config name contains the word Debug for this to happen. E.g. the configuration App-Release-Debug (I know that this would be stupid, but it is for demonstrating purposes) will cause the Packages to include the DEBUG blocks. This happens no matter what you set in the Build Settings of the project and/or target. The Packages are added via GitHub/GitLab Source Control with SPM. Any ideas why this behaves like it does? It doesn't seem like it should...
0
1
64
Mar ’25
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
3
0
134
Apr ’25
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
60
Mar ’25
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
102
Mar ’25
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
53
Mar ’25
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
70
Mar ’25
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.
2
0
359
Mar ’25
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?
6
0
147
Apr ’25
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
65
Mar ’25
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
104
Mar ’25