This topic area is about the programming languages themselves, not about any specific API or tool. If you have an API question, go to the top level and look for a subtopic for that API. If you have a question about Apple developer tools, start in the Developer Tools & Services topic.
For Swift questions:
If your question is about the SwiftUI framework, start in UI Frameworks > SwiftUI.
If your question is specific to the Swift Playground app, ask over in Developer Tools & Services > Swift Playground
If you’re interested in the Swift open source effort — that includes the evolution of the language, the open source tools and libraries, and Swift on non-Apple platforms — check out Swift Forums
If your question is about the Swift language, that’s on topic for Programming Languages > Swift, but you might have more luck asking it in Swift Forums > Using Swift.
General:
Forums topic: Programming Languages
Swift:
Forums subtopic: Programming Languages > Swift
Forums tags: Swift
Developer > Swift website
Swift Programming Language website
The Swift Programming Language documentation
Swift Forums website, and specifically Swift Forums > Using Swift
Swift Package Index website
Concurrency Resources, which covers Swift concurrency
How to think properly about binding memory Swift Forums thread
Other:
Forums subtopic: Programming Languages > Generic
Forums tags: Objective-C
Programming with Objective-C archived documentation
Objective-C Runtime documentation
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Swift
RSS for tagSwift is a powerful and intuitive programming language for Apple platforms and beyond.
Posts under Swift tag
200 Posts
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I'm struggling to implement required code for SB2420 compliance.
I try to learn on a very simple use case.
the app is UIKit
Build in Xcode 26.2
it displays a single Hello view with a button that will simply show a "Good day" label.
I assume the app will be rated 4+.
I tried the following code, using available information in Xcode (limited):
import UIKit
import DeclaredAgeRange
// other import needed ?
class ViewController: UIViewController {
@IBOutlet weak var welcomeLabel: UILabel! // initially hidden
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func testAgeRange() -> Bool {
if !isEligibleForAgeFeatures { // Not found. Which import needed ?
return true // Not called from Texas
}
// Following code from Xcode doc…
do {
let response = try await AgeRangeService.shared.requestAgeRange(ageGates: 13, 15, 18) // Compiler Error: Missing argument for parameter 'in' in call
// Can I add the 4 gate ?
guard let lowerBound = response.lowerBound else {
// Allow access to under 13 features.
return false
}
var ok = false
if lowerBound >= 18 { // Not needed ?
// Allow access to 18+ features.
ok = true
} else if lowerBound >= 15 { // Not needed ?
// Allow access to 15+ features.
ok = true
} else if lowerBound >= 13 { // Not needed ?
// Require parental consent ?
// Allow access to 13+ features.
ok = true // if consent OK
} else {
// Require parental consent ?
// Show age-appropriate content
ok = true // if consent OK
}
return ok // Authorized for all 4+
} catch AgeRangeService.Error.notAvailable {
// No age range provided.
return false
}
}
func executeStart() {
welcomeLabel.isHidden = false
}
@IBAction func start(_ sender: UIButton) {
if #available(iOS 26.0, *) {
if testAgeRange() {
// Need to test for parental control here ?
} else {
// Alert and exit the app ?
}
} else {
// do nothing ? Can we run the app ?
}
executeStart()
}
}
The logic would be:
before allowing action with the start button, check
is it IOS 26+ so that we can call API
if so, is verification needed (Texas SB2420)
if not, we can proceed
if required, test age range
As app is 4+, all ranges should be OK
But need to test parental control
Now, many pending questions in code:
line 14: get an error: Cannot find 'isEligibleForAgeFeatures' in scope
line 19: I used the documentation sample for AgeRangeService, but get a Compiler Error: Missing argument for parameter 'in' in call
line 35: how to implement parental control ?
In addition, in the metadata of the app, should I declare that parental control ?
Age verification?
Mechanism for confirming that a person's age meets the age requirement for accessing content or services
As there is no restriction on age, is it required ?
Any help welcomed as well as link to a comprehensive tutorial.
Currently tested, if the file provider goes offline (referring to calling disconnect) and deletes a file, the system will automatically trigger the deleteItems event after reconnecting (note that only after calling reconnect again will the current deleteItems logic be reached). However, for offline deletion, I would like to pass it directly without operating on the cloud. Can mounting disks determine which operations were performed offline during reboot
Hello,
We are experiencing a behavior change with WKWebView related to upgradeKnownHostsToHTTPS.
Current application, we explicitly disable automatic HTTPS upgrades:
let config = WKWebViewConfiguration()
config.upgradeKnownHostsToHTTPS = false
Observed behavior
iOS 17.5 (built with Xcode 15.3)
http:// image URLs are not automatically upgraded to https://, and the behavior works as expected.
iOS 18.5 / 18.6.x (built with Xcode 16.4)
http:// image URLs appear to be automatically upgraded to https:// by WebKit, even when upgradeKnownHostsToHTTPS is explicitly set to false.
This behavior occurs for subresource requests such as <img src="http://..."> inside a WKWebView.
Question
Has the behavior of upgradeKnownHostsToHTTPS changed in iOS 18 / Xcode 16?
Is this property now ignored for certain types of subresource requests (e.g. images), or overridden by new WebKit security policies such as mixed-content HTTPS upgrades?
Any clarification or official guidance would be greatly appreciated!.
We are developing a hybrid iOS app where Angular content is rendered inside a WKWebView, hosted by a native Swift application.
We use the GameController framework to detect whether an external Bluetooth keyboard is connected to an iPad. The following code is executed when the app enters the foreground and also when requested by the web layer:
func keyboardStatusHandler(){
let isKeyboardConnected = GCKeyboard.coalesced != nil
if(!isKeyboardConnected){
//sent status to Angular
} else {
//sent status to Angular
}
}
Crash details
We are seeing intermittent crashes on iPad with the following stack trace:
Crashed: GCDeviceSession.HID
0 libobjc.A.dylib 0x7db8 objc_retain_x8 + 16
1 libsystem_blocks.dylib 0xfb8 void HelperBase<ExtendedInline>::copyCapture<(HelperBase<ExtendedInline>::BlockCaptureKind)3>(unsigned int) + 48
2 libsystem_blocks.dylib 0xbc4 HelperBase<GenericInline>::copyBlock(Block_layout*, Block_layout*) + 108
3 libsystem_blocks.dylib 0xc94 _call_copy_helpers_excp + 60
4 libsystem_blocks.dylib 0xef8 _Block_copy + 412
5 libdispatch.dylib 0x1a70 _dispatch_Block_copy + 32
6 libdispatch.dylib 0x792c dispatch_async + 56
7 libdispatch.dylib 0x792c dispatch_channel_async + 56
8 GameController 0xea6dc -[GCKeyboardInput _handleKeyboardEvent:] + 324
9 GameController 0x22508 __53-[_GCKeyboardEventHIDAdapter initWithSource:service:]_block_invoke + 376
10 GameController 0x11d30 -[_GCHIDEventSubject publishHIDEvent:] + 268
11 GameController 0xb79cc __40-[_GCHIDEventUIKitClient initWithQueue:]_block_invoke_3 + 44
12 libdispatch.dylib 0x1b584 _dispatch_client_callout + 16
13 libdispatch.dylib 0x12088 _dispatch_async_and_wait_invoke_and_complete_recurse + 272
14 libdispatch.dylib 0x8448 _dispatch_async_and_wait_f + 108
15 GameController 0xb7984 __40-[_GCHIDEventUIKitClient initWithQueue:]_block_invoke_2 + 132
16 GameController 0xb746c __48-[__GCHIDEventUIKitClient _initWithApplication:]_block_invoke + 256
17 UIKitCore 0x11fd394 __61-[UIEventFetcher _setHIDGameControllerEventObserver:onQueue:]_block_invoke_3 + 40
18 libdispatch.dylib 0x1aac _dispatch_call_block_and_release + 32
19 libdispatch.dylib 0x1b584 _dispatch_client_callout + 16
20 libdispatch.dylib 0xa2d0 _dispatch_lane_serial_drain + 740
21 libdispatch.dylib 0xadac _dispatch_lane_invoke + 388
22 libdispatch.dylib 0x151dc _dispatch_root_queue_drain_deferred_wlh + 292
23 libdispatch.dylib 0x14a60 _dispatch_workloop_worker_thread + 540
24 libsystem_pthread.dylib 0xa0c _pthread_wqthread + 292
25 libsystem_pthread.dylib 0xaac start_wqthread + 8
Observed scenarios
Crash occurs when the app transitions from background to foreground
Crash also occurs when the Angular layer requests keyboard status, triggering the same code path
Questions
Has anyone encountered crashes related to GCKeyboard.coalesced or GCKeyboardInput like this?
Are there known issues with the GameController framework when querying keyboard state during app lifecycle transitions?
Is there a recommended or safer way to detect external keyboard connection status on iPad (especially when using WKWebView)?
Any insights, known platform issues, or suggested workarounds would be greatly appreciated.
Thanks!
I am creating a macOs SwiftUI document based app, and I am struggling with the Window sizes and placements. Right now by default, a normal window has the minimize and full screen options which makes the whole window into full screen mode.
However, I don't want to do this for my app. I want to only allow to fill the available width and height, i.e. exclude the status bar and doc when the user press the fill window mode, and also restrict to resize the window beyond a certain point ( which ideally to me is 1200 x 700 because I am developing on macbook air 13.3-inch in which it looks ideal, but resizing it below that makes the entire content inside messed up ).
I want something like this below instead of the default full screen green
When the user presses the button, it should position centered with perfect aspect ratio from my content ( or the one I want like 1200 x 700 ) and can be able to click again to fill the available width and height excluding the status bar and docs.
Here is my entire @main code :-
@main
struct PhiaApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
DocumentGroup(newDocument: PhiaProjectDocument()) { file in
ContentView(
document: file.$document,
rootURL: file.fileURL
)
.configureEditorWindow(disableCapture: true)
.background(AppColors.background)
.preferredColorScheme(.dark)
}
.windowStyle(.hiddenTitleBar)
.windowToolbarStyle(.unified)
.defaultLaunchBehavior(.suppressed)
Settings {
SettingsView()
}
}
}
struct WindowAccessor: NSViewRepresentable {
var callback: (NSWindow?) -> Void
func makeNSView(context: Context) -> NSView {
let view = NSView()
DispatchQueue.main.async { [weak view] in
callback(view?.window)
}
return view
}
func updateNSView(_ nsView: NSView, context: Context) { }
}
extension View {
func configureEditorWindow(disableCapture: Bool = true) -> some View {
self.background(
WindowAccessor { window in
guard let window else { return }
if let screen = window.screen ?? NSScreen.main {
let visible = screen.visibleFrame
window.setFrame(visible, display: true)
window.minSize = visible.size
}
window.isMovable = true
window.isMovableByWindowBackground = false
window.sharingType = disableCapture ? .captureBlocked : .captureAllowed
}
)
}
}
This is a basic setup I did for now, this automatically fills the available width and height on launch, but user can resize and can go beyond my desired min width and height which makes the entire content inside messy.
As I said, I want a native way of doing this, respect the content aspect ratio, don't allow to enter full screen mode, only be able to fill the available width and height excluding the status bar and doc, also don't allow to resize below my desired width and height.
We are getting the above mentioned error while uploading to TestFlight.
We have used a Swift Class to request for the Age Range via DeclaredAgeRange Framework. We have exposed Swift class and a helper function to be available in Objective-C layer. We have enabled the following build settings
SWIFT_OBJC_INTERFACE_HEADER_NAME = "Common-Swift.h";
SWIFT_OBJC_BRIDGING_HEADER = "Common-Bridging-Header.h ";
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES
Also we are compiling the application using latest available Xcode release 17C52
Is there anything else we need to do to resolve the error?
Topic:
App Store Distribution & Marketing
SubTopic:
TestFlight
Tags:
Swift
TestFlight
Declared Age Range
So I’m writing a program, as a developer would - ‘with Xcode.’
Code produced an error.
The key values were swapped. The parameters suggested were ‘optional parameters variables.’
“var name: TYPE? = (default)”
var name0: TYPE
=============================
name0 = “super cool”
‘Name is not yet declared at this point
provided with
x - incorrect argument replace
ExampleStruct(name:”supercool”)
should be
x - incorrect argument replace
ExampleStruct(name0:”supercool”)
=============================
In swift, there is a procedural prioritization within the constructor calling process.
Application calls constructor.
Constructor provides constructor signature. Signature requires parameters & throws an error if the params are not in appropriate order. - “got it compiler; thank you, very much”
Typically, when this occurs, defaults will be suggested. Often the variable type. Ie String, Bool.
such as:
StructName(param1:Int64, param2:Bool)
(Recently, I have seen a decline in @Apple’s performance in many vectors.)
As stated before, the key value pairs were out of sequence. The optionals were suggested instead of the required parameters.
This leads me to believe that there is an order of operations in the calling procedure that is being mismanaged.
I.e. regular expression, matching with optional. This confuses these with [forced, required] parameters, and the mismanagement of ‘key: value’ pairs.
this is a superficial prognosis and would like to know if anyone has any insight as to why this may occur.
Could it be a configuration setting? Is it possibly the network I connected to bumped into something. Etc..
I appreciate any and all feedback.
Please take into consideration the Apple developer forum, guidelines before posting comments.
#dev_div
Hello,
After upgrading to macOS 26.2, I’ve noticed a significant performance regression when calling evaluateJavaScript in an iOS App running on Mac (WKWebView, Swift project).
Observed behavior
On macOS 26.2, the callback of evaluateJavaScript takes around 3 seconds to return.
This happens not only for:
evaluateJavaScript("navigator.userAgent")
but also for simple or even empty scripts, for example:
evaluateJavaScript("")
On previous macOS versions, the same calls typically returned in ~200 ms.
Additional testing
I created a new, empty Objective-C project with a WKWebView and tested the same evaluateJavaScript calls.
In the Objective-C project, the callback still returns in ~200 ms, even on macOS 26.2.
Question
Is this a known issue or regression related to:
iOS Apps on Mac,
Swift + WKWebView, or
behavioral changes in evaluateJavaScript on macOS 26.2?
Any information about known issues, internal changes, or recommended workarounds would be greatly appreciated.
Thank you.
Test Code Swift
class ViewController: UIViewController {
private var tmpWebView: WKWebView?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupUserAgent()
}
func setupUserAgent() {
let t1 = CACurrentMediaTime()
tmpWebView = WKWebView(frame: .zero)
tmpWebView?.isInspectable = true
tmpWebView?.evaluateJavaScript("navigator.userAgent") { [weak self] result, error in
let t2 = CACurrentMediaTime()
print("[getUserAgent] \(t2 - t1)s")
self?.tmpWebView = nil
}
}
}
Test Code Objective-C
- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions {
NSTimeInterval startTime = [[NSDate date] timeIntervalSince1970];
WKWebView *webView = [[WKWebView alloc] init];
dispatch_async(dispatch_get_main_queue(), ^{
[webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
NSTimeInterval endTime = [[NSDate date] timeIntervalSince1970];
NSLog(@"[getUserAgent]: %.2f s", (endTime - startTime));
}];
});
}
I found that the enumerateItems function is only called when a directory is opened for the first time. If the same directory is opened in the future, enumerateItems will not be called again. Can you set or actively trigger the call to the enumerateItems function
I am currently encountering a problem: during the process of uploading a large file, I have moved the file that was not successfully uploaded to the trash can. These two operations have been tested to be serial (triggering the 'create Item' callback first, followed by the 'modify Item' callback), which means that the file must be uploaded before it can be moved to the recycle bin (which can also result in the file being stored in the cloud recycle bin). I want to implement: directly interrupt this upload process and then do not complete the upload. How can I achieve this? Please help me. Thank you
Hi all,
I have a working macOS (Intel) system extension app that currently uses only a Content Filter (NEFilterDataProvider). I need to capture/log HTTP and HTTPS traffic in plain text, and I understand NETransparentProxyProvider is the right extension type for that.
For HTTPS I will need TLS inspection / a MITM proxy — I’m new to that and unsure how complex it will be.
For DNS data (in plain text), can I use the same extension, or do I need a separate extension type such as NEPacketTunnelProvider, NEFilterPacketProvider, or NEDNSProxyProvider?
Current architecture:
Two Xcode targets: MainApp and a SystemExtension target.
The SystemExtension target contains multiple network extension types.
MainApp ↔ SystemExtension communicate via a bidirectional NSXPC connection.
I can already enable two extensions (Content Filter and TransparentProxy). With the NETransparentProxy, I still need to implement HTTPS capture.
Questions I’d appreciate help with:
Can NETransparentProxy capture the DNS fields I need (dns_hostname, dns_query_type, dns_response_code, dns_answer_number, etc.), or do I need an additional extension type to capture DNS in plain text?
If a separate extension is required, is it possible or problematic to include that extension type (Packet Tunnel / DNS Proxy / etc.) in the same SystemExtension Xcode target as the TransparentProxy?
Any recommended resources or guidance on TLS inspection / MITM proxy setup for capturing HTTPS logs?
There are multiple DNS transport types — am I correct that capturing DNS over UDP (port 53) is not necessarily sufficient? Which DNS types should I plan to handle?
I’ve read that TransparentProxy and other extension types (e.g., Packet Tunnel) cannot coexist in the same Xcode target. Is that true?
Best approach for delivering logs from multiple extensions to the main app (is it feasible)? Or what’s the best way to capture logs so an external/independent process (or C/C++ daemon) can consume them?
Required data to capture (not limited to):
All HTTP/HTTPS (request, body, URL, response, etc.)
DNS fields: dns_hostname, dns_query_type, dns_response_code, dns_answer_number, and other DNS data — all in plain text.
I’ve read various resources but remain unclear which extension(s) to use and whether multiple extension types can be combined in one Xcode target. Please ask if you need more details.
Thank you.
Topic:
App & System Services
SubTopic:
Networking
Tags:
Swift
Frameworks
Network Extension
System Extensions
The latest iPhone model is unable to retrieve the Wi-Fi information it has connected to. The phone's operating system is iOS 26.1, and location permission has also been granted.
"Access Wi-Fi Information" is also configured in the same way
The following is the code I used to obtain Wi-Fi information:
func getCurrentWiFiInfo() -> String? {
guard let interfaces = CNCopySupportedInterfaces() as? [String] else {
return nil
}
for interface in interfaces {
guard let info = CNCopyCurrentNetworkInfo(interface as CFString) as? [String: Any] else {
continue
}
if let ssid = info[kCNNetworkInfoKeySSID as String] as? String,
!ssid.isEmpty {
return ssid
}
}
return nil
}
I have implemented the Game Center for authentication and saving player's game data. Both authentication and saving player's data works correctly all the time, but there is a problem with fetching and loading the data.
The game works like this:
At the startup, I start the authentication
After the player successfully logs in, I start loading the player's data by calling fetchSavedGames method
If a game data exists for the player, I receive a list of SavedGame object containing the player's data
The problem is that after I uninstall the game and install it again, sometimes the SavedGame list is empty(step 3). But if I don't uninstall the game and reopen the game, this process works fine.
Here's the complete code of Game Center implementation:
class GameCenterHandler {
public func signIn() {
GKLocalPlayer.local.authenticateHandler = { viewController, error in
if let viewController = viewController {
viewController.present(viewController, animated: false)
return
}
if error != nil {
// Player could not be authenticated.
// Disable Game Center in the game.
return
}
// Auth successfull
self.load(filename: "TestFileName")
}
}
public func save(filename: String, data: String) {
if GKLocalPlayer.local.isAuthenticated {
GKLocalPlayer.local.saveGameData(Data(data.utf8), withName: filename) { savedGame, error in
if savedGame != nil {
// Data saved successfully
}
if error != nil {
// Error in saving game data!
}
}
} else {
// Error in saving game data! User is not authenticated"
}
}
public func load(filename: String) {
if GKLocalPlayer.local.isAuthenticated {
GKLocalPlayer.local.fetchSavedGames { games, error in
if let game = games?.first(where: {$0.name == filename}){
game.loadData { data, error in
if data != nil {
// Data loaded successfully
}
if error != nil {
// Error in loading game data!
}
}
} else {
// Error in loading game data! Filename not found
}
}
} else {
// Error in loading game data! User is not authenticated
}
}
}
I have also added Game Center and iCloud capabilities in xcode. Also in the iCloud section, I selected the iCloud Documents and added a container.
I found a simillar question here but it doesn't make things clearer.
Hello,
I am currently in the process of gradually adding support for LiquidGlass to my app. The transition is taking place incrementally, i.e., new screens and minor features are gradually being adapted to the new design and already deployed.
Currently, the old design is still active via the feature flag UIDesignRequiresCompatibility, as the existing UI should remain locked for the public app store version until the transition is complete.
My challenge is as follows:
I would like to work with the new LiquidGlass design during development without having to manually change the UIDesignRequiresCompatibility flag with each deployment.
Ideally, I am looking for a solution where:
• the new design is only activated for me (e.g., specific account or specific devices)
• the old design remains active for all other users
• the App Store version can be delivered unchanged
So my question is:
Is it possible to control UIDesignRequiresCompatibility via remote config or server-side logic in order to activate the new design specifically for certain users or devices?
I have observed similar behavior on WhatsApp—two devices with the same app version, but only one shows the new design. This suggests server-side or remote config-based control.
Do you have any experience or recommendations on how to implement something like this cleanly?
Kind regards
Heinz
We are using AgeRangeService.requestAgeRange(ageGates:in:) with an age gate of 18 to verify adult users.
The system prompt always displays the lower-bound wording (“17 or Younger”), even when the app’s requirement is to verify users who are 18 or older. We understand the UI is system-controlled; however, this wording causes confusion for users, QA, and product teams, as it appears to indicate a child-only flow even when requesting adult verification.
Based on the demonstration video, it appears that they have another more coherent message.
In Apple's example, it is different, and it is correct that we need to specify 18 years or older in the implementation.
A little more context might be helpful, but we are creating a kind of wrapper with React Native that receives that value as a parameter, which is 18.
It seems Xcode's predictive code completion model is censored. Specifically, when typing the word "torrent," the model stops working completely. It doesn't matter whether the word is written directly in the code or in a comment. It could also be part of another word, such as "qBittorrent." In either case, the model stops working. Reproducing this issue is fairly simple. Create a Swift file and type the word "torrent." The model will stop generating code.
Xcode Version 26.2 (17C52)
Predictive Code Completion Model:
[com.apple.fm.code.generate_small_v2.base: 700.0.81600.13.202379,0] [com.apple.fm.code.generate_safety_guardrail.base: 1.6.81619.13.202072,0] [com.apple.gm.safety_deny.input.code_intelligence.base: 32025010.20251009.91600.100.1651,0] [com.apple.gm.safety_deny.output.code_intelligence.base: 32025010.20251009.91600.100.1651,0] (Installed)
I’m implementing a subscription purchase flow using promo code redemption via an external App Store URL.
Flow:
User taps “Purchase” in the app (spinner shown)
App opens the promo redemption URL (apps.apple.com/redeem)
User completes redemption in the App Store
User returns to the app
The app must determine whether the subscription was purchased within a reasonable time window
The app listens to Transaction.updates and also checks
Transaction.currentEntitlements when the app returns to the foreground.
Issue:
After redeeming a subscription promo code via the App Store and returning to the
app, the app cannot reliably determine whether the subscription was successfully
purchased within a short, user-acceptable time window.
In many cases, neither Transaction.updates nor
Transaction.currentEntitlements reflects the newly redeemed subscription
immediately after returning to the app. The entitlement may appear only after a
significant delay, or not within a 60-second timeout at all, even though the
promo code redemption succeeded.
Expected:
When the user returns to the app after completing promo code redemption,
StoreKit 2 should report the updated subscription entitlement shortly thereafter
(e.g. within a few seconds) via either Transaction.updates or
Transaction.currentEntitlements.
Below is the minimal interactor used in the sample project. The app considers
the purchase successful if either a verified transaction for the product is received via Transaction.updates, or the product appears in Transaction.currentEntitlements when the app returns to the foreground. Otherwise, the flow fails after a 60-second timeout.
Questions:
Is this entitlement propagation delay expected when redeeming promo codes through the App Store?
Is there a recommended API or flow for immediately determining whether a subscription has been successfully redeemed?
Is there a more reliable way to detect entitlement changes after promo code redemption without triggering user authentication prompts (e.g., from AppStore.sync())?
import UIKit
import StoreKit
final class PromoPurchaseInteractor {
private let timeout: TimeInterval = 60
private struct PendingOfferRedemption {
let productId: String
let completion: (Result<Bool, Error>) -> Void
}
private var pendingRedemption: PendingOfferRedemption?
private var updatesTask: Task<Void, Never>?
private var timeoutTask: Task<Void, Never>?
enum DefaultError: Error {
case generic
case timeout
}
init() {
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
updatesTask?.cancel()
timeoutTask?.cancel()
}
func purchaseProduct(using offerUrl: URL, productId: String, completion: @escaping (Result<Bool, Error>) -> Void) {
guard pendingRedemption == nil else {
completion(.failure(DefaultError.generic))
return
}
pendingRedemption = PendingOfferRedemption(productId: productId, completion: completion)
startPurchase(using: offerUrl)
}
@objc private func willEnterForeground() {
guard let pendingRedemption = pendingRedemption else { return }
startTimeoutObserver()
Task {
if await hasEntitlement(for: pendingRedemption.productId) {
await MainActor.run {
self.completePurchase(result: .success(true))
}
}
}
}
private func startPurchase(using offerURL: URL) {
startTransactionUpdatesObserver()
UIApplication.shared.open(offerURL) { [weak self] success in
guard let self = self else { return }
if !success {
self.completePurchase(result: .failure(DefaultError.generic))
}
}
}
private func completePurchase(result: Result<Bool, Error>) {
stopTransactionUpdatesObserver()
stopTimeoutObserver()
guard let _ = pendingRedemption else { return }
pendingRedemption?.completion(result)
pendingRedemption = nil
}
private func startTransactionUpdatesObserver() {
updatesTask?.cancel()
updatesTask = Task {
for await update in Transaction.updates {
guard case .verified(let transaction) = update else { continue }
await MainActor.run { [weak self] in
guard let self = self,
let pending = self.pendingRedemption,
transaction.productID == pending.productId
else { return }
self.completePurchase(result: .success(true))
}
await transaction.finish()
}
}
}
private func stopTransactionUpdatesObserver() {
updatesTask?.cancel()
updatesTask = nil
}
private func startTimeoutObserver() {
guard pendingRedemption != nil else { return }
timeoutTask?.cancel()
timeoutTask = Task {
try? await Task.sleep(nanoseconds: UInt64(timeout * 1_000_000_000))
await MainActor.run { [weak self] in
self?.completePurchase(result: .failure(DefaultError.timeout))
}
}
}
private func stopTimeoutObserver() {
timeoutTask?.cancel()
timeoutTask = nil
}
private func hasEntitlement(for productId: String) async -> Bool {
for await result in Transaction.currentEntitlements {
guard case .verified(let transaction) = result else { continue }
if transaction.productID == productId {
return true
}
}
return false
}
}
I have installed the latest beta on my iPad , iPadOS 16.1 (20B5050f)
On running in app in Playgrounds that has a TextField, external keyboard input do not seem to be working.
Tapping on the Text field inserts the cursor but no text can be entered on my external keyboard.
(TextEditor field also do not work)
Tested with both a Smart Keyboard and a Magic Keyboard.
The keyboard works to enter the code in playgrounds, so it is not a keyboard connection issue.
Disconnecting the keyboard, the onscreen keyboard is displayed and works correctly.
Is this a Playgrounds issue or an iPadOS 16.1 issue or a compatibility issue with Playgrounds & iPadOS 16.1 ?
import SwiftUI
struct ContentView: View {
@State var field: String = "Test input"
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
Text("Hello, world!")
TextField("", text: $field)
.frame(height: 100)
}
}
}
Moving the cursor left and right becomes extremely sluggish, though up-down movement and mouse clicks are normal. The Apple Store Genius checked the hardware and even reinstalled the OS, but the issue remains.
Topic:
Developer Tools & Services
SubTopic:
Swift Playground
Tags:
Developer Tools
Swift
Swift Playground
We are facing a DNS resolution issue with a specific ISP, where our domain name does not resolve correctly using the system DNS. However, the same domain works as expected when a custom DNS resolver is used.
On Android, this is straightforward to handle by configuring a custom DNS implementation using OkHttp / Retrofit. I am trying to implement a functionally equivalent solution in native iOS (Swift / SwiftUI).
**Android Reference (Working Behavior) : **
val dns = DnsOverHttps.Builder()
.client(OkHttpClient())
.url("https://cloudflare-dns.com/dns-query".toHttpUrl()) .bootstrapDnsHosts(InetAddress.getByName("1.1.1.1")).build()
OkHttpClient.Builder().dns(dns).build()
**Attempted iOS Approach **
I attempted the following approach :
Resolve the domain to an IP address programmatically (using DNS over HTTPS)
Connect directly to the resolved IP address
Set the original domain in the Host HTTP header
**DNS Resolution via DoH : **
func resolveDomain(domain: String) async throws -> String {
guard let url = URL(
string: "https://cloudflare-dns.com/dns-query?name=\(domain)&type=A"
) else {
throw URLError(.badURL)
}
var request = URLRequest(url: url)
request.setValue("application/dns-json", forHTTPHeaderField: "accept")
let (data, _) = try await URLSession.shared.data(for: request)
let response = try JSONDecoder().decode(DNSResponse.self, from: data)
guard let ip = response.Answer?.first?.data else {
throw URLError(.cannotFindHost)
}
return ip
}
**API Call Using Resolved IP : **
func callAPIUsingCustomDNS() async throws {
let ip = try await resolveDomain(domain: "example.com")
guard let url = URL(string: "https://\(ip)") else {
throw URLError(.badURL)
}
let configuration = URLSessionConfiguration.ephemeral
let session = URLSession(
configuration: configuration,
delegate: CustomURLSessionDelegate(originalHost: "example.com"),
delegateQueue: .main
)
var request = URLRequest(url: url)
request.setValue("example.com", forHTTPHeaderField: "Host")
let (_, response) = try await session.data(for: request)
print("Success: \(response)")
}
**Problem Encountered **
When connecting via the IP address, the TLS handshake fails with the following error:
Error Domain=NSURLErrorDomain Code=-1200
"A TLS error caused the secure connection to fail."
This appears to happen because iOS sends the IP address as the Server Name Indication (SNI) during the TLS handshake, while the server’s certificate is issued for the domain name.
**Custom URLSessionDelegate Attempt : **
class CustomURLSessionDelegate: NSObject, URLSessionDelegate {
let originalHost: String
init(originalHost: String) {
self.originalHost = originalHost
}
func urlSession(
_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
) {
guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
let serverTrust = challenge.protectionSpace.serverTrust else {
completionHandler(.performDefaultHandling, nil)
return
}
let sslPolicy = SecPolicyCreateSSL(true, originalHost as CFString)
let basicPolicy = SecPolicyCreateBasicX509()
SecTrustSetPolicies(serverTrust, [sslPolicy, basicPolicy] as CFArray)
var error: CFError?
if SecTrustEvaluateWithError(serverTrust, &error) {
completionHandler(.useCredential, URLCredential(trust: serverTrust))
} else {
completionHandler(.cancelAuthenticationChallenge, nil)
}
}
}
However, TLS validation still fails because the SNI remains the IP address, not the domain.
I would appreciate guidance on the supported and App Store–compliant way to handle ISP-specific DNS resolution issues on iOS. If custom DNS or SNI configuration is not supported, what alternative architectural approaches are recommended by Apple?