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
After the iOS 26 update, unwanted animations appear on UIButton.
I'm using the attributedTitle property of UIButton.Configuration to change the button's text, and an animation appears after iOS 26.
(It's unclear whether it's after iOS 26.0 or iOS 26.1, but it likely started with 26.1.)
The peculiar thing is that the animation only starts appearing on buttons that have been pressed once.
I tried using UIView.performWithoutAnimation and CATransaction's begin(), setDisableActions(true), commit(), but it didn't work.
How should I solve this?
Below is the code for changing the button's text.
func updateTitle() {
let keys = type.keys
if keys.count == 1 {
guard let key = keys.first else { return }
if key.count == 1 {
if Character(key).isLowercase {
self.configuration?.attributedTitle = AttributedString(key, attributes: AttributeContainer([.font: UIFont.systemFont(ofSize: 24, weight: .regular), .foregroundColor: UIColor.label]))
} else if Character(key).isUppercase {
self.configuration?.attributedTitle = AttributedString(key, attributes: AttributeContainer([.font: UIFont.systemFont(ofSize: 22, weight: .regular), .foregroundColor: UIColor.label]))
} else {
self.configuration?.attributedTitle = AttributedString(key, attributes: AttributeContainer([.font: UIFont.systemFont(ofSize: 22, weight: .regular), .foregroundColor: UIColor.label]))
}
} else {
self.configuration?.attributedTitle = AttributedString(key, attributes: AttributeContainer([.font: UIFont.systemFont(ofSize: 18, weight: .regular), .foregroundColor: UIColor.label]))
}
} else {
let joined = keys.joined(separator: "")
self.configuration?.attributedTitle = AttributedString(joined, attributes: AttributeContainer([.font: UIFont.systemFont(ofSize: 22, weight: .regular), .foregroundColor: UIColor.label]))
}
}
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
I want to implement a feature on macOS using FileProvider: only grant the allowsTrashing permission to files that have already been downloaded, while not granting it to dataless files. However, the system will automatically drain and clear the content. How can this be detected (and how to determine whether a file is dataless)
Since updating to Tahoe and Xcode 26 I have found that the UISplitViewController.showDetailViewController() is not working in the iPhone version of my app (it is a universal app). I'm just trying to show a detail view after a tap on a UITableView item. The iPad versions are all working correctly. Has anyone else experienced this or have any advice about what may have changed?
Thanks in advance.
I'm building a macOS app using SwiftUI, and I want to create a draggable floating webcam preview window
Right now, I have something like this:
import SwiftUI
import AVFoundation
struct WebcamPreviewView: View {
let captureSession: AVCaptureSession?
var body: some View {
ZStack {
if let session = captureSession {
CameraPreviewLayer(session: session)
.clipShape(RoundedRectangle(cornerRadius: 50))
.overlay(
RoundedRectangle(cornerRadius: 50)
.strokeBorder(Color.white.opacity(0.2), lineWidth: 2)
)
} else {
VStack(spacing: 8) {
Image(systemName: "video.slash.fill")
.font(.system(size: 40))
.foregroundColor(.white.opacity(0.6))
Text("No Camera")
.font(.caption)
.foregroundColor(.white.opacity(0.6))
}
}
}
.shadow(color: .black.opacity(0.3), radius: 10, x: 0, y: 5)
}
}
struct CameraPreviewLayer: NSViewRepresentable {
let session: AVCaptureSession
func makeNSView(context: Context) -> NSView {
let view = NSView()
view.wantsLayer = true
let previewLayer = AVCaptureVideoPreviewLayer(session: session)
previewLayer.videoGravity = .resizeAspectFill
previewLayer.frame = view.bounds
view.layer = previewLayer
return view
}
func updateNSView(_ nsView: NSView, context: Context) {
if let previewLayer = nsView.layer as? AVCaptureVideoPreviewLayer {
previewLayer.frame = nsView.bounds
}
}
}
This is my SwiftUI side code to show the webcam, and I am trying to create it as a floating window which appears on top of all other apps windows etc. however, even when the webcam is clicked, it should not steal the focus from other apps, the other apps should be able to function properly as they already are.
import Cocoa
import SwiftUI
class WebcamPreviewWindow: NSPanel {
private static let defaultSize = CGSize(width: 200, height: 200)
private var initialClickLocation: NSPoint = .zero
init() {
let screenFrame = NSScreen.main?.visibleFrame ?? .zero
let origin = CGPoint(
x: screenFrame.maxX - Self.defaultSize.width - 20,
y: screenFrame.minY + 20
)
super.init(
contentRect: CGRect(origin: origin, size: Self.defaultSize),
styleMask: [.borderless],
backing: .buffered,
defer: false
)
isOpaque = false
backgroundColor = .clear
hasShadow = false
level = .screenSaver
collectionBehavior = [
.canJoinAllSpaces,
.fullScreenAuxiliary,
.stationary,
.ignoresCycle
]
ignoresMouseEvents = false
acceptsMouseMovedEvents = true
hidesOnDeactivate = false
becomesKeyOnlyIfNeeded = false
}
// MARK: - Focus Prevention
override var canBecomeKey: Bool { false }
override var canBecomeMain: Bool { false }
override var acceptsFirstResponder: Bool { false }
override func makeKey() {
}
override func mouseDown(with event: NSEvent) {
initialClickLocation = event.locationInWindow
}
override func mouseDragged(with event: NSEvent) {
let current = event.locationInWindow
let dx = current.x - initialClickLocation.x
let dy = current.y - initialClickLocation.y
let newOrigin = CGPoint(
x: frame.origin.x + dx,
y: frame.origin.y + dy
)
setFrameOrigin(newOrigin)
}
func show<Content: View>(with view: Content) {
let host = NSHostingView(rootView: view)
host.autoresizingMask = [.width, .height]
host.frame = contentLayoutRect
contentView = host
orderFrontRegardless()
}
func hide() {
orderOut(nil)
contentView = nil
}
}
This is my Appkit Side code make a floating window, however, when the webcam preview is clicked, it makes it as the focus app and I have to click anywhere else to loose the focus to be able to use the rest of the windows.
A functioning Multiplatform app, which includes use of Continuity Camera on an M1MacMini running Sequoia 15.5, works correctly capturing photos with AVCapturePhoto. However, that app (and a test app just for Continuity Camera) crashes at delegate callback when run on a 2017 MacBookPro under MacOS 13.7.5. The app was created with Xcode 16 (various releases) and using Swift 6 (but tried with 5). Compiling and running the test app with Xcode 15.2 on the 13.7.5 machine also crashes at delegate callback.
The iPhone 15 Continuity Camera gets detected and set up correctly, and preview video works correctly. It's when the CapturePhoto code is run that the crash occurs.
The relevant capture code is:
func capturePhoto() {
let captureSettings = AVCapturePhotoSettings()
captureSettings.flashMode = .auto
photoOutput.maxPhotoQualityPrioritization = .quality
photoOutput.capturePhoto(with: captureSettings, delegate: PhotoDelegate.shared)
print("**** CameraManager: capturePhoto")
}
and the delegate callbacks are:
class PhotoDelegate: NSObject, AVCapturePhotoCaptureDelegate {
nonisolated(unsafe) static let shared = PhotoDelegate()
// MARK: - Delegate callbacks
func photoOutput(
_ output: AVCapturePhotoOutput,
didFinishProcessingPhoto photo: AVCapturePhoto,
error: (any Error)?
) {
print("**** CameraManager: didFinishProcessingPhoto")
guard let pData = photo.fileDataRepresentation() else {
print("**** photoOutput is empty")
return
}
print("**** photoOutput data is \(pData.count) bytes")
}
func photoOutput(
_ output: AVCapturePhotoOutput,
willBeginCaptureFor resolvedSettings: AVCaptureResolvedPhotoSettings
) {
print("**** CameraManager: willBeginCaptureFor")
}
func photoOutput(_ output: AVCapturePhotoOutput, willCapturePhotoFor resolvedSettings: AVCaptureResolvedPhotoSettings) {
print("**** CameraManager: willCaptureCapturePhotoFor")
}
}
The crash report significant parts are.....
Crashed Thread: 3 Dispatch queue: com.apple.cmio.CMIOExtensionProviderHostContext
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x0000000000000000
Exception Codes: 0x0000000000000001, 0x0000000000000000
Termination Reason: Namespace SIGNAL, Code 11 Segmentation fault: 11
Terminating Process: exc handler [30850]
VM Region Info: 0 is not in any region. Bytes before following region: 4296495104
REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL
UNUSED SPACE AT START
--->
__TEXT 100175000-10017f000 [ 40K] r-x/r-x SM=COW ...tinuityCamera
Thread 0:: Dispatch queue: com.apple.main-thread
0 libsystem_kernel.dylib 0x7ff803aed552 mach_msg2_trap + 10
1 libsystem_kernel.dylib 0x7ff803afb6cd mach_msg2_internal + 78
2 libsystem_kernel.dylib 0x7ff803af4584 mach_msg_overwrite + 692
3 libsystem_kernel.dylib 0x7ff803aed83a mach_msg + 19
4 CoreFoundation 0x7ff803c07f8f __CFRunLoopServiceMachPort + 145
5 CoreFoundation 0x7ff803c06a10 __CFRunLoopRun + 1365
6 CoreFoundation 0x7ff803c05e51 CFRunLoopRunSpecific + 560
7 HIToolbox 0x7ff80d694f3d RunCurrentEventLoopInMode + 292
8 HIToolbox 0x7ff80d694d4e ReceiveNextEventCommon + 657
9 HIToolbox 0x7ff80d694aa8 _BlockUntilNextEventMatchingListInModeWithFilter + 64
10 AppKit 0x7ff806ca59d8 _DPSNextEvent + 858
11 AppKit 0x7ff806ca4882 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1214
12 AppKit 0x7ff806c96ef7 -[NSApplication run] + 586
13 AppKit 0x7ff806c6b111 NSApplicationMain + 817
14 SwiftUI 0x7ff90e03a9fb 0x7ff90dfb4000 + 551419
15 SwiftUI 0x7ff90f0778b4 0x7ff90dfb4000 + 17578164
16 SwiftUI 0x7ff90e9906cf 0x7ff90dfb4000 + 10340047
17 ContinuityCamera 0x10017b49e 0x100175000 + 25758
18 dyld 0x7ff8037d1418 start + 1896
Thread 1:
0 libsystem_pthread.dylib 0x7ff803b27bb0 start_wqthread + 0
Thread 2:
0 libsystem_pthread.dylib 0x7ff803b27bb0 start_wqthread + 0
Thread 3 Crashed:: Dispatch queue: com.apple.cmio.CMIOExtensionProviderHostContext
0 ??? 0x0 ???
1 AVFCapture 0x7ff82045996c StreamAsyncStillCaptureCallback + 61
2 CoreMediaIO 0x7ff813a4358f __94-[CMIOExtensionProviderHostContext captureAsyncStillImageWithStreamID:uniqueID:options:reply:]_block_invoke + 498
3 libxpc.dylib 0x7ff803875b33 _xpc_connection_reply_callout + 36
4 libxpc.dylib 0x7ff803875ab2 _xpc_connection_call_reply_async + 69
5 libdispatch.dylib 0x7ff80398b099 _dispatch_client_callout3 + 8
6 libdispatch.dylib 0x7ff8039a6795 _dispatch_mach_msg_async_reply_invoke + 387
7 libdispatch.dylib 0x7ff803991088 _dispatch_lane_serial_drain + 393
8 libdispatch.dylib 0x7ff803991d6c _dispatch_lane_invoke + 417
9 libdispatch.dylib 0x7ff80399c3fc _dispatch_workloop_worker_thread + 765
10 libsystem_pthread.dylib 0x7ff803b28c55 _pthread_wqthread + 327
11 libsystem_pthread.dylib 0x7ff803b27bbf start_wqthread + 15
Of course, the MacBookPro is an old device - but Continuity Camera works with the installed Photo Booth app, so it's possible.
Any thoughts on solving this situation would be appreciated.
Regards, Michaela
We have a login flow where the user authenticates in Safari, and at the end of the process the authentication server redirects back to our app using a Universal Link.
On most devices, the app opens automatically without any confirmation banner.
However, on several iPads, Safari always shows the “Open App A?” banner after the redirect. The user must tap Open every time. Other devices running the same iOS version do not show this issue.
Expected Flow (working devices):
Start authentication
Safari login
Authentication server redirects using a Universal Link
App A opens automatically
Problematic Flow (several iPads):
Start authentication
Safari login
Authentication server redirects using a Universal Link
Safari shows “Open App A?” confirmation banner
User must tap Open
App A starts
Questions:
Is this a known issue in iOS?
Or is this expected behavior under certain conditions (i.e., is there a specific Safari/iOS specification that causes this banner to appear)?
Is there any way to prevent Safari from showing the “Open App A?” banner and allow automatic redirection?
*This issue did not occur on iOS 16, but it started appearing after updating to iOS 17.
Devices :
iPad 9th Gen/iPad 10th Gen
I am trying to use Zone Sharing in my SwiftUI app. I have been attempting to get the UICloudSharingController to show an initial share screen to pick users and the mechanism to send the invitation.
From the documentation, it appears that the UICloudSharingController .init(preparationHandler:) API is deprecated so I am not using that approach. Following the Apple documentation, I am creating a Zone Share and NOT saving it and presenting using the UICloudSharingController(share:container:) API. However, this presents a UI that is the 'mgmt' API for a Share. I can get to the UI I was expecting by tapping on the 'Share with More People' option, but I want to start on that screen for the user when they have not shared this before.
So, I found an example app from Apple at: https://github.com/apple/sample-cloudkit-zonesharing. It has the same behavior. So we can simply discuss this problem based on that example code.
How do I get the next View presented when tapping 'Share Group' to be the invitation for new users screen?
Here is the UI it presents initially:
And here is the UI (on the bottom half of the screen) I am trying to start the share process with:
Thanks,
Charlie
After switching our iOS app project from Swift 5 to Swift 6 and publishing an update, we started seeing a large number of crashes in Firebase Crashlytics.
The crashes are triggered by NotificationCenter methods (post, addObserver, removeObserver) and show the following error:
BUG IN CLIENT OF LIBDISPATCH: Assertion failed: Block was expected to execute on queue [com.apple.main-thread (0x1f9dc1580)]
All scopes to related calls are already explicitly marked with @MainActor. This issue never occurred with Swift 5, but appeared immediately after moving to Swift 6.
Has anyone else encountered this problem? Is there a known solution or workaround?
Thanks in advance!
I created a Notification Service Extension to display profile images in place for the app image (i.e. iMessage).
I send a remote push notification via Firebase Functions, and in the payload, the relevant profile image url string. The profile image url string in the payload is successfully delivered as it appears in my console log and AppDelegate didReceiveRemoteNotification function.
My problem is the profile image does not replace the default app icon image in the remote push notification.
Below is my configuration. Any guidance would be appreciated!
Main target app: the info plist contains NSUSerActivityTypes = [INSendMessageIntent]. The Communications Notifications capability is enabled and "Copy only when installing" in Build Phases Embed Foundation Extensions
Notification Service Extension plist: contains NSExtension > NSExtensionAttributes > IntentsSupported > INSendMessageIntent.
Notification Service Extension class code:
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
guard var bestAttemptContent = bestAttemptContent else { return }
guard let fcmOptions = bestAttemptContent.userInfo["fcm_options"] as? [String: Any],
let attachmentUrlAsString = fcmOptions["imageURL"] as? String else {
contentHandler(bestAttemptContent)
return
}
if let attachmentUrl = URL(string: attachmentUrlAsString) {
var senderNameComponents = PersonNameComponents()
senderNameComponents.nickname = bestAttemptContent.title
let profileImage = INImage(url: attachmentUrl)
let sender = INPerson(personHandle: INPersonHandle(value: "1233211234", type: .unknown), nameComponents: senderNameComponents, displayName: bestAttemptContent.title, image: profileImage, contactIdentifier: nil, customIdentifier: nil, isMe: false)
let receiver = INPerson(personHandle: INPersonHandle(value: "1233211234", type: .unknown), nameComponents: nil, displayName: nil, image: nil, contactIdentifier: nil, customIdentifier: nil, isMe: true)
let intent = INSendMessageIntent(
recipients: [receiver],
outgoingMessageType: .outgoingMessageText,
content: "Test",
speakableGroupName: INSpeakableString(spokenPhrase: "Sender Name"),
conversationIdentifier: "sampleConversationIdentifier",
serviceName: nil,
sender: sender,
attachments: nil
)
intent.setImage(profileImage, forParameterNamed: \.sender)
let interaction = INInteraction(intent: intent, response: nil)
interaction.direction = .incoming
interaction.donate(completion: nil)
if #available(iOSApplicationExtension 15.0, *) {
do {
bestAttemptContent = try bestAttemptContent.updating(from: intent) as! UNMutableNotificationContent
} catch {
contentHandler(bestAttemptContent)
return
}
}
contentHandler(bestAttemptContent)
} else {
contentHandler(bestAttemptContent)
return
}
}
}
In my case, when I try to block calls on iOS 26, the blocking doesn't occur; the scenarios seem intermittent. If I create two CallDirectory extensions, the first blocks the numbers, but the second doesn't. Interestingly, the extension marks the number as suspicious. There's also a case where, on iOS 26 on an iPhone 16 Pro, the functionality doesn't work at all. I'd like to know if there have been any changes to the use of CallKit in iOS 26, because users of my app on iOS 18 and below report successful blocking.
I got several reports about our TestFlight app crashing unconditionally on 2 devices (iOS 18.1 and iOS 18.3.1) on app start with the following reason:
Termination Reason: DYLD 4 Symbol missing
Symbol not found: _$sScIsE4next7ElementQzSgyYa7FailureQzYKF
(terminated at launch; ignore backtrace)
The symbol in question demangles to
(extension in Swift):Swift.AsyncIteratorProtocol.next() async throws(A.Failure) -> A.Element?
Our deploy target is iOS 18.0, this symbol was introduced in Swift 6.0, we're using latest Xcode 16 now - everything should be working, but for some reason aren't.
Since this symbol is quite rarely used directly, I was able to pinpoint the exact place in code related to it. Few days ago I added the following code to our app library (details omitted):
public struct AsyncRecoveringStream<Base: AsyncSequence>: AsyncSequence {
...
public struct AsyncIterator: AsyncIteratorProtocol {
...
public mutating func next(isolation actor: isolated (any Actor)? = #isolation) async throws(Failure) -> Element? {
...
}
}
}
I tried to switch to Xcode 26 - it was still crashing on affected phone. Then I changed next(isolation:) to its older version, next():
public mutating func next() async throws(Failure) -> Element?
And there crashes are gone. However, this change is a somewhat problematic, since I either have to lower Swift version of our library from 6 to 5 and we loose concurrency checks and typed throws or I'm loosing tests due to Swift compiler crash. Performance is also affected, but it's not that critical for our case.
Why is this crash happening? How can I solve this problem or elegantly work around it?
Thank you!
2025-10-09_17-13-31.7885_+0100-23e00e377f9d43422558d069818879042d4c5c2e.crash
When a static library is built with Xcode 26 (with deployment target set to iOS 13) and then linked into an app project compiled with Xcode 16, the build process fails with the following linker error:
Undefined symbols for architecture arm64:
"_swift_coroFrameAlloc"
This occurs even though both the static library and the app project have their deployment targets set to iOS 13.0. The static library works on Xcode 26, but fails to link on Xcode 16.
This issue shows up with certain Swift syntax. For example, in my case, using a property getter and setter caused the compiler to emit a reference to _swift_coroFrameAlloc, which in turn triggered the issue.
This issue prevents us from distributing pre-built static libraries compiled with Xcode 26 to teammates who are still using Xcode 16.
I’ve filed feedback for this issue (FB21130604).
Is there any way to work around it? For example, by adding specific Build Settings or something similar?
A demo project is available here: https://github.com/Naituw/SwiftLibraryDeploymentTargetIssue
The demo project includes:
StaticLibraryProject: A simple Swift static library with property getter setter usage
AppProject: An iOS app that links against the static library
verify_compatibility.sh: An automated script to reproduce the issue
Method 1: Manual Build and Verification
Open StaticLibraryProject/StaticLibraryProject.xcodeproj in Xcode 26
Build the StaticLibraryProject for iOS device (Release configuration)
Locate the built libStaticLibraryProject.a in the build products directory
Copy libStaticLibraryProject.a to AppProject/AppProject/ directory
Open AppProject/AppProject.xcodeproj in Xcode 16
Build the AppProject for iOS device
Method 2: Automated Script
Edit verify_compatibility.sh to configure the paths to your Xcode installations:
Set XCODE_26_PATH to your Xcode 26 installation path (e.g., /Applications/Xcode.app)
Set XCODE_16_PATH to your Xcode 16 installation path (e.g., /Applications/Xcode16.app)
Run the script: ./verify_compatibility.sh
I have made a screensaver for mac in swift, but couldn't find how to add an icon the logo image that shows up on saver file) and thumbnail (the cover image that shows up in the screensaver catalogue).
Currently, it just shows a default blue spiral galaxy thumbnail and no icon image
Like any good developer, I try to add tests where I can. The AgeRangeService.AgeRange type does not provide an initializer. I know the routine, create an interface or a simple struct that I control and use that instead. Thanks to extensive time with frameworks like Core Bluetooth or Core Location, this is a well understood practice (looking at you CBPeripheral...).
Great I'll make my own 'AgeRange' struct. Make it Hashable, make it Sendable, use the framework types as properties. Scratch that, most of the properties on AgeRangeService.AgeRange type are not Sendable and many are also not Hashable. This is proving to be challenging.
I hope to open source my little Swift Package wrapper library for DeclaredAgeRange which will add types with full Hashable and Sendable conformance. I hope Apple updates the API and makes this obsolete. I don't see why these simple types can't be Hashable and Sendable. They're structs, enums, and OptionSets (structs).
FB20959748 - DeclaredAgeRange: DeclaredAgeRangeAction is not sendable causing main actor compile errors with default isolation settings
FB20960560 - DeclaredAgeRange: AgeRangeService.AgeRangeDeclaration is not sendable as expected
FB20960574 - DeclaredAgeRange: AgeRangeService.ParentalControls is not sendable as expected
FB20960590 - DeclaredAgeRange: AgeRangeService.ParentalControls is not hashable as expected
On the note of the library and using the types as-is, there are some issues using the new cases in AgeRangeDeclaration and the isEligibelForAgeFeatures property. I started another thread over here: https://developer.apple.com/forums/thread/808144
Topic:
App Store Distribution & Marketing
SubTopic:
General
Tags:
Swift
Beta
Testing
Declared Age Range
Hi, does anyone know how to enable creating or configuring Near NFC Reader in SwiftUI?
I've already added the capability, the permissions in info.plist, the entitlement, and the SwiftUI code, but without success. Here's the example code:
class PaymentT2PViewModel: NSObject, ObservableObject {
@Published var paymentT2PUIState: PaymentT2PUIState
// MARK: - NFC Properties
@Published var nfcMessage: String = .empty
@Published var isNFCReading: Bool = false
private var nfcSession: NFCTagReaderSession?
init(paymentT2PUIState: PaymentT2PUIState) {
self.paymentT2PUIState = paymentT2PUIState
super.init()
)
}
func startNFCReading() {
print("INICIO: startNFCReading llamado")
guard NFCTagReaderSession.readingAvailable else {
print("ERROR: NFC NO disponible en este dispositivo")
Task { @MainActor in
self.nfcMessage = "NFC no disponible en este dispositivo"
}
return
}
print("NFC disponible, creando sesión...")
nfcSession = NFCTagReaderSession(
pollingOption: [.iso14443, .iso15693, .iso18092],
delegate: self,
queue: nil
)
print("Sesión creada, configurando mensaje...")
nfcSession?.alertMessage = "Acerca la tarjeta al iPhone"
nfcSession?.begin()
print("Sesión NFC INICIADA - debería aparecer popup")
Task { @MainActor in
self.isNFCReading = true
}
}
func stopNFCReading() {
nfcSession?.invalidate()
Task { @MainActor in
self.isNFCReading = false
}
}
extension PaymentT2PViewModel: NFCTagReaderSessionDelegate {
func tagReaderSession(_ session: NFCTagReaderSession, didInvalidateWithError error: Error) {
print("SESIÓN INVALIDADA")
print("Error: (error.localizedDescription)")
if let readerError = error as? NFCReaderError {
print("Código de error: \(readerError.code.rawValue)")
print("¿Es cancelación del usuario?: \(readerError.code == .readerSessionInvalidationErrorUserCanceled)")
}
Task { @MainActor in
if let readerError = error as? NFCReaderError {
if readerError.code != .readerSessionInvalidationErrorUserCanceled {
self.nfcMessage = "Error: \(readerError.localizedDescription)"
}
}
self.isNFCReading = false
}
}
func tagReaderSessionDidBecomeActive(_ session: NFCTagReaderSession) {
print("NFC Session activa")
}
func tagReaderSession(_ session: NFCTagReaderSession, didDetect tags: [NFCTag]) {
guard let firstTag = tags.first else { return }
session.connect(to: firstTag) { [weak self] error in
if let error = error {
session.invalidate(errorMessage: "Error al conectar: \(error.localizedDescription)")
return
}
Task { @MainActor [weak self] in
await self?.handleTag(firstTag, session: session)
}
}
}
private func handleTag(_ tag: NFCTag, session: NFCTagReaderSession) async {
switch tag {
case .iso7816(let tag):
await handleISO7816Tag(tag, session: session)
case .miFare(let tag):
await handleMiFareTag(tag, session: session)
case .iso15693(let tag):
await handleISO15693Tag(tag, session: session)
case .feliCa(let tag):
await handleFeliCaTag(tag, session: session)
@unknown default:
session.invalidate(errorMessage: "Tipo de tag no soportado")
}
}
private func handleISO7816Tag(_ tag: NFCISO7816Tag, session: NFCTagReaderSession) async {
let uid = tag.identifier.map { String(format: "%02X", $0) }.joined()
nfcMessage = """
ISO7816 Tag detectado
UID: \(uid)
Historical Bytes: \(tag.historicalBytes?.map { String(format: "%02X", $0) }.joined() ?? "N/A")
"""
session.alertMessage = "Tag leído exitosamente"
session.invalidate()
}
private func handleMiFareTag(_ tag: NFCMiFareTag, session: NFCTagReaderSession) async {
let uid = tag.identifier.map { String(format: "%02X", $0) }.joined()
nfcMessage = """
MiFare Tag detectado
UID: \(uid)
Tipo: \(tag.mifareFamily.description)
"""
session.alertMessage = "Tag leído exitosamente"
session.invalidate()
}
private func handleISO15693Tag(_ tag: NFCISO15693Tag, session: NFCTagReaderSession) async {
let uid = tag.identifier.map { String(format: "%02X", $0) }.joined()
nfcMessage = """
ISO15693 Tag detectado
UID: \(uid)
IC Manufacturer: \(tag.icManufacturerCode)
"""
session.alertMessage = "Tag leído exitosamente"
session.invalidate()
}
private func handleFeliCaTag(_ tag: NFCFeliCaTag, session: NFCTagReaderSession) async {
let idm = tag.currentIDm.map { String(format: "%02X", $0) }.joined()
let pmm = tag.currentSystemCode.map { String(format: "%02X", $0) }.joined()
nfcMessage = """
FeliCa Tag detectado
IDm: \(idm)
System Code: \(pmm)
"""
session.alertMessage = "Tag leído exitosamente"
session.invalidate()
}
}
// MARK: - Helper Extension
extension NFCMiFareFamily {
var description: String {
switch self {
case .unknown: return "Desconocido"
case .ultralight: return "Ultralight"
case .plus: return "Plus"
case .desfire: return "DESFire"
@unknown default: return "Otro"
}
}
}
struct PaymentT2PView: View {
@ObservedObject var paymentT2PViewModel: PaymentT2PViewModel
var body: some View {
ZStack {
if paymentT2PViewModel.paymentT2PUIState.showingResult {
print("Navigate")
} else {
print("False")
}
}
.onAppear {
paymentT2PViewModel.startNFCReading()
}
.onDisappear {
paymentT2PViewModel.stopNFCReading()
}
}}
However, I'm getting code error messages, and I'm testing this on an iPhone 11.
What am I doing wrong?
Hi everyone,
I am encountering an issue where my Live Activity (Dynamic Island) suddenly became invalid and failed to launch. It was working perfectly before, and I haven't modified any code since then.
My Environment:
Xcode: 26.1.1
Device iOS: 26.1
Testing: I also tested on iOS 18, but the Live Activity fails to start there as well.
Here is my code:
Live Activity Manager (Start/Update/End):
func startLiveActivity() {
// Initial static data
let attributes = SimpleIslandAttributes(name: "Test Order")
// Initial dynamic data
let initialContentState = SimpleIslandState(message: "Preparing...")
// Adapting for iOS 16.2+ new API (Content)
let activityContent = ActivityContent(state: initialContentState, staleDate: nil)
do {
let activity = try Activity.request(
attributes: attributes,
content: activityContent,
pushType: nil // Set to nil as remote push updates are not needed
)
print("Live Activity Started ID: \(activity.id)")
} catch {
print("Failed to start: \(error.localizedDescription)")
}
}
// 2. Update Live Activity
func updateLiveActivity() {
Task {
let updatedState = SimpleIslandState(message: "Delivering 🚀")
let updatedContent = ActivityContent(state: updatedState, staleDate: nil)
// Iterate through all active Activities and update them
for activity in Activity<SimpleIslandAttributes>.activities {
await activity.update(updatedContent)
print("Update")
}
}
}
// 3. End Live Activity
func endLiveActivity() {
Task {
let finalState = SimpleIslandState(message: "Delivered ✅")
let finalContent = ActivityContent(state: finalState, staleDate: nil)
for activity in Activity<SimpleIslandAttributes>.activities {
// dismissalPolicy: .default (immediate), .after(...) (delayed), .immediate (no animation)
await activity.end(finalContent, dismissalPolicy: .default)
print("End")
}
}
}
The Models (Shared between App and Widget Extension):
// 1. Define State (Dynamic data, changes over time, e.g., remaining delivery time)
public struct SimpleIslandState: Codable, Hashable {
var message: String
}
// 2. Define Attributes (Static data, constant after start, e.g., Order ID)
public struct SimpleIslandAttributes: ActivityAttributes {
public typealias ContentState = SimpleIslandState
var name: String // e.g., "My Order"
}
The Widget Code:
//
// SimpleIslandWidget.swift
// ReadyGo
//
// Created by Tang Yu on 2025/11/19.
//
import WidgetKit
import SwiftUI
import ActivityKit
struct SimpleIslandWidget: Widget {
var body: some WidgetConfiguration {
ActivityConfiguration(for: SimpleIslandAttributes.self) { context in
// UI shown on the Lock Screen
VStack {
Text("Lock Screen Notification: \(context.state.message)")
}
.activityBackgroundTint(Color.cyan)
.activitySystemActionForegroundColor(Color.black)
} dynamicIsland: { context in
// Inside Widget Extension
DynamicIsland {
// Expanded Region
DynamicIslandExpandedRegion(.center) {
Text("Test") // Pure text only
}
} compactLeading: {
Text("L") // Pure text only
} compactTrailing: {
Text("R") // Pure text only
} minimal: {
Text("M") // Pure text only
}
}
}
}
Additional Info:
This is the minimal code setup I created for testing, but even this basic version is failing.
I have set NSSupportsLiveActivities (Supports Live Activities) to YES (true) in the Info.plist for both the Main App and the Widget Extension.
Has anyone experienced this? Any help would be appreciated.
I’m integrating the Declared Age Range feature to tailor our app’s experience based on a user’s age range. I’m currently in the testing phase and would like to repeatedly test the consent flow and different outcomes from AgeRangeService.shared.requestAgeRange(...).
However, once I go through the consent flow and choose to share, the age-range sharing sheet no longer appears on subsequent attempts—so it’s hard to validate edge cases (e.g., changed gates, declined flow, re-prompt behavior).
Could you advise on the recommended way to reset or re-prompt during development? In particular:
Is there a supported way to clear per-app consent so the system prompts again?
Under what conditions should the “Share Age Range Again” control appear in Settings, and is there an equivalent way to trigger it for testing?
Are there best practices for QA (e.g., using Ask First at the system level, testing on real devices vs. Simulator, using a separate bundle ID for dev builds, or other steps)?
Any other guidance for validating different requestAgeRange results (e.g., declined/not available) would be appreciated.
I’m building a macOS video editor that uses AVComposition and AVVideoComposition.
Initially, my renderer creates a composition with some default video/audio tracks:
@Published var composition: AVComposition?
@Published var videoComposition: AVVideoComposition?
@Published var playerItem: AVPlayerItem?
Then I call a buildComposition() function that inserts all the default video segments.
Later in the editing workflow, the user may choose to add their own custom video clip. For this I have a function like:
private func handlePickedVideo(_ url: URL) {
guard url.startAccessingSecurityScopedResource() else {
print("Failed to access security-scoped resource")
return
}
let asset = AVURLAsset(url: url)
let videoTracks = asset.tracks(withMediaType: .video)
guard let firstVideoTrack = videoTracks.first else {
print("No video track found")
url.stopAccessingSecurityScopedResource()
return
}
renderer.insertUserVideoTrack(from: asset, track: firstVideoTrack)
url.stopAccessingSecurityScopedResource()
}
What I want to achieve is the same behavior professional video editors provide,
after the composition has already been initialized and built, the user should be able to add a new video track and the composition should update live, meaning the preview player should immediately reflect the changes without rebuilding everything from scratch manually.
How can I structure my AVComposition / AVMutableComposition and my rendering pipeline so that adding a new clip later updates the existing composition in real time (similar to Final Cut/Adobe Premiere), instead of needing to rebuild everything from zero?
You can find a playable version of this entire setup at :- https://github.com/zaidbren/SimpleEditor
After updating from iOS 26 to iOS 26.1, all my transparent system elements (i.e. UITabBar, UIBarButtonItem) started rendering with a dark background tint. In iOS 26 the same configuration looked fully transparent / glassy.
The strange part is that the tint only appears in normal UIViewControllers. In UITableViewController the tab bar still looks correct and transparent, even on iOS 26.1.
I am using the same appearance code as before:
func setupTabBarAppearance() {
guard let tabBar = tabBarController?.tabBar else { return }
if #available(iOS 26.0, *) {
let appearance = UITabBarAppearance()
appearance.configureWithTransparentBackground()
appearance.backgroundColor = .clear
appearance.backgroundEffect = nil
appearance.shadowColor = .clear
tabBar.standardAppearance = appearance
tabBar.scrollEdgeAppearance = appearance
tabBar.isTranslucent = true
tabBar.backgroundColor = .clear
tabBar.barTintColor = .clear
} else {
tabBar.isTranslucent = true
tabBar.backgroundImage = UIImage()
tabBar.shadowImage = UIImage()
tabBar.backgroundColor = .clear
}
}
I tried removing backgroundEffect, forcing .clear colors, using configureWithDefaultBackground, changing edgesForExtendedLayout, extendedLayoutIncludesOpaqueBars, etc. I noticed that if I change Liquid Glass in iOS 26 settings from Clear to Tinted, then I get a black tint everywhere and the interface becomes consistent, but not the way I want.
Nothing removes the new dark tint in iOS 26.1. Is this an intentional change in iOS 26.1, a bug, or is there a new way to make the tab bar fully transparent again?