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

Posts under Swift tag

200 Posts

Post

Replies

Boosts

Views

Activity

The behavior of AVPlayerItem.didPlayToEndTimeNotification is not as expected in iOS 26.
Hello, Environment macOS 15.6.1 / Xcode 26 beta 7 / iOS 26 Beta 9 In a simple AVFoundation video-playback sample, I’m seeing different behavior between iOS 18 and iOS 26 regarding AVPlayerItem.didPlayToEndTimeNotification. I’ve attached a minimal sample below. Please replace videoURL with a valid short video URL. Repro steps Tap “Play” to start playback and let the video finish. The AVPlayerItem.didPlayToEndTimeNotification registered with NotificationCenter should fire, and you should see Play finished. in the console. Without relaunching, tap “Play” again. This is where the issue arises. Observed behavior On iOS 18 and earlier: The video does not play again (it does not restart from the beginning), but AVPlayerItem.didPlayToEndTimeNotification is posted and Play finished. appears in the console. The same happens every time you press “Play”. On iOS 26: Pressing “Play” does not post AVPlayerItem.didPlayToEndTimeNotification. The code path that prints Play finished. is never called (the callback enclosing that line is not invoked again). Building the same program with Xcode 16.4 and running it on an iOS 26 beta device shows the same phenomenon, which suggests there has been a behavioral change for AVPlayerItem.didPlayToEndTimeNotification on iOS 26. I couldn’t find any mention of this in the release notes or API Reference. Because the semantics around AVPlayerItem.didPlayToEndTimeNotification appear to differ, we’re forced to adjust our logic. If there is a way to achieve the iOS 18–style behavior on iOS 26, I would appreciate guidance. Alternatively, if this change is intentional, could you share the reasoning? Is iOS 26 the correct behavior from Apple’s perspective and iOS 18 (and earlier) behavior considered incorrect? Any official clarification would be extremely helpful. import UIKit import AVFoundation final class ViewController: UIViewController { private let videoURL = URL(string: "https://......mp4")! private var player: AVPlayer? private var playerItem: AVPlayerItem? private var playerLayer: AVPlayerLayer? private var observeForComplete: NSObjectProtocol? // UI private let playerContainerView = UIView() private let playButton = UIButton(type: .system) private let stopButton = UIButton(type: .system) private let replayButton = UIButton(type: .system) deinit { if let observeForComplete { NotificationCenter.default.removeObserver(observeForComplete) } } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground setupUI() setupPlayer() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() playerLayer?.frame = playerContainerView.bounds } // MARK: - Setup private func setupUI() { playerContainerView.translatesAutoresizingMaskIntoConstraints = false playerContainerView.backgroundColor = .black view.addSubview(playerContainerView) // Buttons playButton.setTitle("Play", for: .normal) stopButton.setTitle("Pause", for: .normal) replayButton.setTitle("RePlay", for: .normal) [playButton, stopButton, replayButton].forEach { $0.titleLabel?.font = .systemFont(ofSize: 16, weight: .semibold) $0.translatesAutoresizingMaskIntoConstraints = false $0.contentEdgeInsets = UIEdgeInsets(top: 10, left: 16, bottom: 10, right: 16) } let stack = UIStackView(arrangedSubviews: [playButton, stopButton, replayButton]) stack.axis = .horizontal stack.spacing = 16 stack.alignment = .center stack.distribution = .equalCentering stack.translatesAutoresizingMaskIntoConstraints = false view.addSubview(stack) NSLayoutConstraint.activate([ playerContainerView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20), playerContainerView.leadingAnchor.constraint(equalTo: view.leadingAnchor), playerContainerView.trailingAnchor.constraint(equalTo: view.trailingAnchor), playerContainerView.heightAnchor.constraint(equalToConstant: 200), stack.topAnchor.constraint(equalTo: playerContainerView.bottomAnchor, constant: 20), stack.centerXAnchor.constraint(equalTo: view.centerXAnchor) ]) // Action playButton.addTarget(self, action: #selector(didTapPlay), for: .touchUpInside) stopButton.addTarget(self, action: #selector(didTapStop), for: .touchUpInside) replayButton.addTarget(self, action: #selector(didTapReplayFromStart), for: .touchUpInside) } private func setupPlayer() { // AVURLAsset -> AVPlayerItem → AVPlayer let asset = AVURLAsset(url: videoURL) let item = AVPlayerItem(asset: asset) self.playerItem = item let player = AVPlayer(playerItem: item) player.automaticallyWaitsToMinimizeStalling = true self.player = player let layer = AVPlayerLayer(player: player) layer.videoGravity = .resizeAspect playerContainerView.layer.addSublayer(layer) layer.frame = playerContainerView.bounds self.playerLayer = layer // Notification if let observeForComplete { NotificationCenter.default.removeObserver(observeForComplete) } if let playerItem { observeForComplete = NotificationCenter.default.addObserver( forName: AVPlayerItem.didPlayToEndTimeNotification, object: playerItem, queue: .main ) { [weak self] _ in guard self != nil else { return } Task { @MainActor in print("Play finished.") } } } } // MARK: - Actions @objc private func didTapPlay() { player?.play() } @objc private func didTapStop() { player?.pause() } // RePlay @objc private func didTapReplayFromStart() { player?.seek(to: .zero, toleranceBefore: .zero, toleranceAfter: .zero) { [weak self] _ in self?.player?.play() } } } I would greatly appreciate an official response from Apple engineering on whether this is an intentional change, a regression, or an API contract clarification, and what the recommended approach is going forward. Thank you.
2
1
351
2h
Using Glass in SwiftUI Crashes with Missing Weak Symbol
My Xcode project fails to run with the following crash log any time I use a new SwiftUI symbol such as ConcentricRectangle or .glassEffect. I've tried using the legacy linker to no avail. It compiles perfectly fine, and I've tried targeting just macOS 26 also to no avail. This is a macOS project that's compiled just fine for years and compiles and runs on macOS going back to 13.0. Failed to look up symbolic reference at 0x118e743cd - offset 1916987 - symbol symbolic _____y_____y_____y_____yAAyAAy_____y__________G_____G_____yAFGGSg_ACyAAy_____y_____SSG_____y_____SgGG______tGSgACyAAyAAy_____ATG_____G_AVtGSgtGGAQySbGG______Qo_ 7SwiftUI4ViewPAAE11glassEffect_2inQrAA5GlassV_qd__tAA5ShapeRd__lFQO AA15ModifiedContentV AA6VStackV AA05TupleC0V AA01_hC0V AA9RectangleV AA5ColorV AA12_FrameLayoutV AA24_BackgroundStyleModifierV AA6IDViewV 8[ ]012EditorTabBarC0V AA022_EnvironmentKeyWritingS0V A_0W0C AA7DividerV A_0w4JumpyC0V AA08_PaddingP0V AA07DefaultgeH0V in /Users/[ ]/Library/Developer/Xcode/DerivedData/[ ]-grfjhgtlsyiobueapymobkzvfytq/Build/Products/Debug/[ ]/Contents/MacOS/[ ].debug.dylib - pointer at 0x119048408 is likely a reference to a missing weak symbol Example crashing code: import SwiftUI struct MyView: View { var body: some View { if #available(macOS 26.0, *) { Text("what the heck man").glassEffect() } } }
4
0
179
7h
toolbar buttons not showing sometimes after upgraded to iPadOS26.
(Sorry if this is not the right place to post...) I upgraded my iPad / macOS to 26 yesterday. Soon, I noticed that the two buttons in the toolbar would sometimes not appear: Note that they should be visible at all times. I played a little more to see if there was any pattern, but I could not find any. Has anyone experienced something similar...? Is this an iPadOS26 bug? (I haven't checked with an iPhone yet.) Thanks.
Topic: UI Frameworks SubTopic: General Tags:
0
0
30
12h
CarPlay app not receiving data updates when iPhone screen is locked
We are building a CarPlay app and have run into an issue with data updates. When the app is running on the CarPlay display and the iPhone screen is locked, no data updates are shown on the CarPlay screen. As soon as the phone is unlocked, the data updates appear instantly on the CarPlay display. Has anyone encountered this behavior before? Is there a specific setting, entitlement, or background mode we need to enable in order to ensure the CarPlay app continues to receive and display data while the iPhone is locked? Any guidance would be greatly appreciated.
1
1
100
1d
Customization in Swift ArgumentParser's help command and error output
Hello I want to implement customisation to swift argumentparser, Here are following changes want to do it in my cli changing default footer present in help command output currently help command output coming like this OVERVIEW: clisample USAGE: clisample <subcommand> OPTIONS: --version show the version. -h, --help show the help. SUBCOMMANDS: logs (default) Export logs for clisample processes. See 'clisample --help' for more information.' so instead of See 'clisample --help' for more information.' I want my own string For more details, run 'clisample help <subcommand>' customise error string getting from validation error Error: Missing value for '-t <time>' Help: -t <time> Time window (e.g. 10h, 30m, 2d). Usage: clisample logs --time <time> See 'clisample logs --help' for more information. so I want error output with example and customised footer, like this Error: Missing value for '-t <time>' Help: -t <time> Time window (e.g. 10h, 30m, 2d). Usage: clisample logs --time <time> Example: clisample logs -t 5m For more details, run 'clisample help <subcommand>' Is this changes possible from anyway?
1
0
476
5d
iOS 26 UIKIt: Where's the missing cornerConfiguration property of UIViewEffectView?
In WWDC25 video 284: Build a UIKit app with the new design, there is mention of a cornerConfiguration property on UIVisualEffectView. But this properly isn't documented and Xcode 26 isn't aware of any such property. I'm trying to replicate the results of that video in the section titled Custom Elements starting at the 19:15 point. There is a lot of missing details and typos in the code associated with that video. My attempts with UIGlassEffect and UIViewEffectView do not result in any capsule shapes. I just get rectangles with no rounded corners at all. As an experiment, I am trying to recreate the capsule with the layers/location buttons in the iOS 26 version of the Maps app. I put the following code in a view controller's viewDidLoad method let imgCfgLayer = UIImage.SymbolConfiguration(hierarchicalColor: .systemGray) let imgLayer = UIImage(systemName: "square.2.layers.3d.fill", withConfiguration: imgCfgLayer) var cfgLayer = UIButton.Configuration.plain() cfgLayer.image = imgLayer let btnLayer = UIButton(configuration: cfgLayer, primaryAction: UIAction(handler: { _ in print("layer") })) var cfgLoc = UIButton.Configuration.plain() let imgLoc = UIImage(systemName: "location") cfgLoc.image = imgLoc let btnLoc = UIButton(configuration: cfgLoc, primaryAction: UIAction(handler: { _ in print("location") })) let bgEffect = UIGlassEffect() bgEffect.isInteractive = true let bg = UIVisualEffectView(effect: bgEffect) bg.contentView.addSubview(btnLayer) bg.contentView.addSubview(btnLoc) view.addSubview(bg) btnLayer.translatesAutoresizingMaskIntoConstraints = false btnLoc.translatesAutoresizingMaskIntoConstraints = false bg.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ btnLayer.leadingAnchor.constraint(equalTo: bg.contentView.leadingAnchor), btnLayer.trailingAnchor.constraint(equalTo: bg.contentView.trailingAnchor), btnLayer.topAnchor.constraint(equalTo: bg.contentView.topAnchor), btnLoc.centerXAnchor.constraint(equalTo: bg.contentView.centerXAnchor), btnLoc.topAnchor.constraint(equalTo: btnLayer.bottomAnchor, constant: 15), btnLoc.bottomAnchor.constraint(equalTo: bg.contentView.bottomAnchor), bg.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor), bg.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40), ]) The result is pretty close other than the complete lack of capsule shape. What changes would be needed to get the capsule shape? Is this even the proper approach?
12
5
611
5d
Is there a way to disable NFC on iPhones?
I have some logic which requires NFC support on the device. This is what I'm using to make sure that it's available: isNFCMissing = !NFCNDEFReaderSession.readingAvailable && !NFCTagReaderSession.readingAvailable && !NFCVASReaderSession.readingAvailable Is it possible for isNFCMissing to be true even if the device has an NFC chip. The minimum iOS version for the application is 16 which is only supported on devices with an NFC chip to begin with.
2
0
142
5d
iOS 26 Toolbar with UITabAccessory(UITabbarController.bottomAccessory)
Hi, When pushing a view controller with a toolbar onto a UITabBarController that has a bottom accessory, the toolbar and bottom accessory overlap. UITabbarController has a bottomAccessory AViewController push BViewController. And BViewController.hidesBottomBarWhenPushed = true Xcode version : Xcode 26.0 Release Cantidate sample code let flexible = if #available(iOS 26.0, *) { UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) } else { UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) } let isMemo = isMemo let emailItem = UIBarButtonItem(image: UIImage(named: "batch_gray_email.png"), style: .plain, target: self, action: #selector(onEmailTapped)) let deleteItem = UIBarButtonItem(image: UIImage(named: "batch_gray_bin.png"), style: .plain, target: self, action: #selector(onDeleteTapped)) deleteItem.tintColor = .systemRed let editItem = UIBarButtonItem(image: UIImage(named: "batch_gray_compose.png"), style: .plain, target: self, action: #selector(onEditTapped)) let memoItem = UIBarButtonItem(image: UIImage(named: "batch_note.png"), style: .plain, target: self, action: #selector(onMemoTapped)) if isMemo { setToolbarItems([flexible, deleteItem, flexible, memoItem, flexible], animated: true) } else { setToolbarItems([emailItem, flexible, deleteItem, flexible, editItem, flexible, memoItem], animated: true) } AViewController *detailViewController = [[AViewController alloc]init]; detailViewController.hidesBottomBarWhenPushed = YES; [self.navigationController pushViewController:detailViewController animated:true];
Topic: UI Frameworks SubTopic: UIKit Tags:
0
0
64
6d
Swift Package Manager – Support for Multiple Targets with Distinct Localization Files
I am an SDK provider working with Swift Package Manager (SPM) to deliver libraries for iOS developers. My SDK currently uses SPM targets to modularize functionality. However, SPM enforces strict resource bundling, which prevents me from efficiently offering multiple targets—each with a different set of localization files—in a single package. Current Limitation: When multiple SPM targets share the same source and resource directory but require distinct sets of .lproj localization folders (for app size or client requirements), SPM raises “overlapping sources” errors. The only workaround is to manually split resource directories or have clients prune localizations post-build, which is inefficient and error-prone. Feature Request: Please consider adding native support in Swift Package Manager for: Defining multiple targets within a single package that can process overlapping source/resource directories, Each target specifying a distinct subset of localization resource files via the exclude or a new designated parameter, Enabling efficient modular delivery of SDKs to clients needing different localization payloads, without redundant resource duplication or error-prone manual pruning. Support for this feature would greatly ease SDK distribution, lower app sizes, and improve package maintainability for iOS and all Swift platforms.
0
0
859
1w
Building a bidirectional, infinitely scrolling list using ScrollView - challenges and potential solutions
I have been banging my head against this problem for a bit now. I am trying to build a bidirectional, infinitely scrolling list that implements these core requirements: Loads data up/down on the fly as the user scrolls Preserves scroll velocity as the list is updated Restores the scroll to the exact visual location after data has changed Ensures no flicker when restoring scroll position - the user cannot know the list has updated and should continue scrolling as normal Because LazyVStack does not play well with animations, I am opting to go with VStack and am implementing my own sliding window for data. This means that data can be removed as well as added, and a simple application of a height delta is not enough when restoring position. So far I have tried many things: Relying on ScrollPosition - simply does not work by itself as described (swift UI trying to keep the position stable with ID's) Relying on ScrollPosition.scrollTo - only kind of works with ID, no way to restore position with pixel perfect accuracy Intercepting the UIKit scrollView instance, using it to record and access the top row's position, mutating data and then queuing a scroll restoration using CATransaction.setCompletionBlock - this is the closest I've come, and it satisfies the top 3 requirements but sometimes I get a flicker on slightly heavier lists What I would really like, is a way of using ScrollView and granularly hooking into the lifecycle of the view after layout, and just before draw. At this point I would update the relevant scroll positions, and allow draw to continue. Is this possible? My knowledge is very limited at this point, but I believe I may be able to achieve something of the sort by swizzling layerWillDraw? Does this make sense, and is it prudent? In general, I'm very interesting in hearing what people have to say about the above, as well as this problem in general.
2
0
209
1w
Is it possible to read and write layout before render with SwiftUI?
I’m trying to keep a specific row visually stable while the data backing a ScrollView changes. Goal 1. Before updating model.items, capture the top row’s offset relative to the scroll view. 2. Mutate the observable state so SwiftUI recomputes layout — but don’t draw yet. 3. Read the new layout, compute the delta, and adjust the scroll position so the previously visible row stays put. 4. Only then draw the new frame. Reduced example @Observable final class SomeModel { var items: [SomeItem] = [/* ... */] } struct MyBox: View { @Environment(SomeModel.self) private var model var body: some View { ScrollView { VStack { ForEach(model.items, id: \.id) { item in Color.red.frame(height: randomStableHeight(for: item.id)) } } } } } // Elsewhere: let oldRow = recordOldRow() // capture the row to stabilize model.items = generateNewItems() // mutate model (invalidates layout) let newPos = capturePreviousRowNewPosition(oldRow) // read new layout? restoreScrollPosition() // adjust so oldRow stays visually fixed // draw now Is that pipeline achievable in SwiftUI? If not, what’s the supported way to keep a row visually stable while the list updates?
1
0
51
1w
NWConnection: how to recover data connection after RF cellular data connection loss
iOS Development environment Xcode 16.4, macOS 15.6.1 (24G90) Run-time configuration: iOS 17.2+ Short Description After having successfully established an NWConnection (either as UDP or TCP), and subsequently receiving the error code: UDP Connection failed: 57 The operation couldn't be completed. (Network.NWError error 57 - Socket is not connected), available Interfaces: [enO] via NWConnection.stateUpdateHandler = { (newState) in ... } while newState == .failed the data connection does not restart by itself once cellular (RF) telephony coverage is established again. Detailed Description Context: my app has a continuous cellular data connection while in use. Either a UDP or a TCP connection is established depending on the user settings. The setup data connection works fine until the data connection gets disconnected by loss of connection to a available cellular phone base station. This disconnection simply occurs in very poor UMTS or GSM cellular phone coverage. This is totally normal behavior in bad reception areas like in mountains with signal loss. STEPS TO REPRODUCE Pre-condition App is running with active data connection. Action iPhone does loss the cellular data connection previously setup. Typically reported as network error code 57. Observed The programmed connection.stateUpdateHandler() is called in network connection state '.failed' (OK). The self-programmed data re-connection includes: a call to self.connection.cancel() a call to self.setupUDPConnection() or self.setupConnection() depending on the user settings to re-establish an operative data connection. However, the iPhone's UMTS/GSM network data (re-)connection state is not properly identified/notified via NWConnection API. There's no further network state notification by means of NWConnection even though the iPhone has recovered a cellular data network. Expected The iPhone or any other means automatically reconnects the interrupted data connection on its own. The connection.stateUpdateHandler() is called at time of the device's networking data connection (RF) recovering, subsequently to a connection state failed with error code 57, as the RF module is continuously (independently from the app) for available telephony networks. QUESTION How to systematically/properly detect a cellular phone data network reconnection readiness in order to causally reinitialize the NWConnection data connection available used in app. Relevant code extract Setup UDP connection (or similarly setup a TCP connection) func setupUDPConnection() { let udp = NWProtocolUDP.Options.init() udp.preferNoChecksum = false let params = NWParameters.init(dtls: nil, udp: udp) params.serviceClass = .responsiveData // service type for medium-delay tolerant, elastic and inelastic flow, bursty, and long-lived connections connection = NWConnection(host: NWEndpoint.Host.name(AppConstant.Web.urlWebSafeSky, nil), port: NWEndpoint.Port(rawValue: AppConstant.Web.urlWebSafeSkyPort)!, using: params) connection.stateUpdateHandler = { (newState) in switch (newState) { case .ready: //print("UDP Socket State: Ready") self.receiveUDPConnection(). // data reception works fine until network loss break case .setup: //print("UDP Socket State: Setup") break case .cancelled: //print("UDP Socket State: Cancelled") break case .preparing: //print("UDP Socket State: Preparing") break case .waiting(let error): Logger.logMessage(message: "UDP Connection waiting: "+error.errorCode.description+" \(error.localizedDescription), available Interfaces: \(self.connection.currentPath!.availableInterfaces.description)", LoggerLevels.Error) break case .failed(let error): Logger.logMessage(message: "UDP Connection failed: "+error.errorCode.description+" \(error.localizedDescription), available Interfaces: \(self.connection.currentPath!.availableInterfaces.description)", LoggerLevels.Error) // data connection retry (expecting network transport layer to be available) self.reConnectionServer() break default: //print("UDP Socket State: Waiting or Failed") break } self.handleStateChange() } connection.start(queue: queue) } Handling of network data connection loss private func reConnectionServer() { self.connection.cancel() // Re Init Connection - Give a little time to network recovery let delayInSec = 30.0. // expecting actually a notification for network data connection availability, instead of a time-triggered retry self.queue.asyncAfter(deadline: .now() + delayInSec) { switch NetworkConnectionType { case 1: self.setupUDPConnection() // UDP break case 2: self.setupConnection() // TCP break default: break } } } Does it necessarily require the use of CoreTelephony class CTTelephonyNetworkInfo or class CTCellularData to get notifications of changes to the user’s cellular service provider?
7
0
149
1w
CloudKit Query on Custom Indexed Field fails with misleading "createdBy is not queryable" error
Hello everyone, I am experiencing a persistent authentication error when querying a custom user profile record, and the error message seems to be a red herring. My Setup: I have a custom CKRecord type called ColaboradorProfile. When a new user signs up, I create this record and store their hashed password, salt, nickname, and a custom field called loginIdentifier (which is just their lowercase username). In the CloudKit Dashboard, I have manually added an index for loginIdentifier and set it to Queryable and Searchable. I have deployed this schema to Production. The Problem: During login, I run an async function to find the user's profile using this indexed loginIdentifier. Here is the relevant authentication code: func autenticar() async { // ... setup code (isLoading, etc.) let lowercasedUsername = username.lowercased() // My predicate ONLY filters on 'loginIdentifier' let predicate = NSPredicate(format: "loginIdentifier == %@", lowercasedUsername) let query = CKQuery(recordType: "ColaboradorProfile", predicate: predicate) // I only need these specific keys let desiredKeys = ["password", "passwordSalt", "nickname", "isAdmin", "isSubAdmin", "username"] let database = CKContainer.default().publicCloudDatabase do { // This is the line that throws the error let result = try await database.records(matching: query, desiredKeys: desiredKeys, resultsLimit: 1) // ... (rest of the password verification logic) } catch { // The error always lands here logDebug("Error authenticating with CloudKit: \(error.localizedDescription)") await MainActor.run { self.errorMessage = "Connection Error: \(error.localizedDescription)" self.isLoading = false self.showAlert = true } } } The Error: Even though my query predicate only references loginIdentifier, the catch block consistently reports this error: Error authenticating with CloudKit: Field 'createdBy' is not marked queryable. I know createdBy (the system creatorUserRecordID) is not queryable by default, but my query isn't touching that field. I already tried indexing createdBy just in case, but the error persists. It seems CloudKit cannot find or use my index for loginIdentifier and is incorrectly reporting a fallback error related to a system field. Has anyone seen this behavior? Why would CloudKit report an error about createdBy when the query is explicitly on an indexed, custom field? I'm new to Swift and I'm struggling quite a bit. Thank you,
0
0
121
1w
Drag-and-Drop from macOS Safari to NSItemProvider fails due to URL not being a file:// URL
(Using macOS 26 Beta 9 and Xcode 26 Beta 7) I am trying to support basic onDrop from a source app to my app. I am trying to get the closest "source" representation of a drag-and-drop, e.g. a JPEG file being dropped into my app shouldn't be converted, but stored as a JPEG in Data. Otherwise, everything gets converted into TIFFs and modern iPhone photos get huge. I also try to be a good app, and provide asynchronous support. Alas, I've been running around for days now, where I can now support Drag-and-Drop from the Finder, from uncached iCloud files with Progress bar, but so far, drag and dropping from Safari eludes me. My code is as follows for the onDrop support: Image(nsImage: data.image).onDrop(of: Self.supportedDropItemUTIs, delegate: self) The UTIs are as follows: public static let supportedDropItemUTIs: [UTType] = [ .image, .heif, .rawImage, .png, .tiff, .svg, .heic, .jpegxl, .bmp, .gif, .jpeg, .webP, ] Finally, the code is as follows: public func performDrop(info: DropInfo) -> Bool { let itemProviders = info.itemProviders(for: Self.supportedDropItemUTIs) guard let itemProvider = itemProviders.first else { return false } let registeredContentTypes = itemProvider.registeredContentTypes guard let contentType = registeredContentTypes.first else { return false } var suggestedName = itemProvider.suggestedName if suggestedName == nil { switch contentType { case UTType.bmp: suggestedName = "image.bmp" case UTType.gif: suggestedName = "image.gif" case UTType.heic: suggestedName = "image.heic" case UTType.jpeg: suggestedName = "image.jpeg" case UTType.jpegxl: suggestedName = "image.jxl" case UTType.png: suggestedName = "image.png" case UTType.rawImage: suggestedName = "image.raw" case UTType.svg: suggestedName = "image.svg" case UTType.tiff: suggestedName = "image.tiff" case UTType.webP: suggestedName = "image.webp" default: break } } let progress = itemProvider.loadInPlaceFileRepresentation(forTypeIdentifier: contentType.identifier) { url, _, error in if let error { print("Failed to get URL from dropped file: \(error)") return } guard let url else { print("Failed to get URL from dropped file!") return } let queue = OperationQueue() queue.underlyingQueue = .global(qos: .utility) let intent = NSFileAccessIntent.readingIntent(with: url, options: .withoutChanges) let coordinator = NSFileCoordinator() coordinator.coordinate(with: [intent], queue: queue) { error in if let error { print("Failed to coordinate data from dropped file: \(error)") return } do { // Load file contents into Data object let data = try Data(contentsOf: intent.url) Dispatch.DispatchQueue.main.async { self.data.data = data self.data.fileName = suggestedName } } catch { print("Failed to load coordinated data from dropped file: \(error)") } } } DispatchQueue.main.async { self.progress = progress } return true } For your information, this code is at the state where I gave up and sent it here, because I cannot find a solution to my issue. Now, this code works everywhere, except for dragging and dropping from Safari. Let's pretend I go to this web site: https://commons.wikimedia.org/wiki/File:Tulip_Tulipa_clusiana_%27Lady_Jane%27_Rock_Ledge_Flower_Edit_2000px.jpg and I try to drag-and-drop the image, it will fail with the following error: URL https://upload.wikimedia.org/wikipedia/commons/c/cf/Tulip_Tulipa_clusiana_%27Lady_Jane%27_Rock_Ledge_Flower_Edit_2000px.jpg is not a file:// URL. And then, fail with the dreaded Failed to get URL from dropped file: Error Domain=NSItemProviderErrorDomain Code=-1000 As far as I can tell, the problem lies in the opaque NSItemProvider receiving a web site URL from Safari. I tried most solutions, I couldn't retrieve that URL. The error happens in the callback of loadInPlaceFileRepresentation, but also fails in loadFileRepresentation. I tried hard-requesting a loadObject of type URL, but there's only one representation for the JPEG file. I tried only putting .url in the requests, but it would not transfer it. Anyone solved this mystery?
5
0
145
1w
App rejected for non-public symbols _BIO_s_socket and _OPENSSL_cleanse from third-party library
Hi, My app was recently rejected with the following message: The app references non-public symbols in App: _BIO_s_socket, _OPENSSL_cleanse The confusing part is that these symbols do not come from iOS system libraries. They are defined inside a third-party static library (gRPC/OpenSSL) that my app links. I am not calling any Apple private API, only linking against the third-party code where those symbols are defined. Questions: Why does App Review treat these symbols as “non-public” when they are provided by my own bundled third-party library, not by the system? What is Apple’s recommended approach in this situation — should I rebuild the third-party library with symbol renaming / hidden visibility, or is there another supported method? It would help to understand the official reasoning here, because it seems strange that a vendor-namespaced or self-built OpenSSL would cause a rejection even though I am not using Apple’s internal/private APIs. Thanks for any clarification.
2
0
121
1w
IOS cursor control
My app controls the cursor movement in a text view on iPhone and iPads. On screen touch, the IOS cursor position is out of sync with the app cursor position. Is there a way to find out, on screen touch, where the ios cursor positition is and update the app cursor to the ios cursor position? When they are out of sync, the user has to move the cursor to the startIndex and navigate from there. Frustating! I have looked at many programming books, forums, and internet search with nothing to no avail. Any help will be greatly appreciated. The app names are SummaGramPhonex and SummaGramIPAD11 and SummaGramIPAD13. Thanks. Charlie 3Sep25
0
0
139
2w
Tab bar controller drag and drop order of items not working
Hi I'm using Xcode 16.4 on a Mac mini m4 so please let's not get in the weeds about latest this or that for software, etc... I'm trying to move one of the tab bar items in the controller, the home item, the the far left and I can grab it and drag it but it won't drop anywhere except where it exists. the other items won't move either. I've googled this and not finding anything stating you have to do a key combo, etc... which I've tried the command, option and control keys each with the dragging. Also the ability to actually select and item to drag it is extremely inconsistent, sometimes it grabs it and most of the time it doesn't. do I need to just delete the connectors and add them back in the proper order? is that really the solution here?
3
0
85
2w
Core Data + CKSyncEngine with Swift 6 — concurrency, Sendable, and best practices validation
Hi everyone, I’ve been working on migrating my app (SwimTimes, which helps swimmers track their times) to use Core Data + CKSyncEngine with Swift 6. After many iterations, forum searches, and experimentation, I’ve created a focused sample project that demonstrates the architecture I’m using. The good news: 👉 I believe the crashes I was experiencing are now solved, and the sync behavior is working correctly. 👉 The demo project compiles and runs cleanly with Swift 6. However, before adopting this as the final architecture, I’d like to ask the community (and hopefully Apple engineers) to validate a few critical points, especially regarding Swift 6 concurrency and Core Data contexts. Architecture Overview Persistence layer: Persistence.swift sets up the Core Data stack with a main viewContext and a background context for CKSyncEngine. Repositories: All Core Data access is abstracted into repository classes (UsersRepository, SwimTimesRepository), with async/await methods. SyncEngine: Wraps CKSyncEngine, handles system fields, sync tokens, and bridging between Core Data entities and CloudKit records. ViewModels: Marked @MainActor, exposing @Published arrays for SwiftUI. They never touch Core Data directly, only via repositories. UI: Simple SwiftUI views bound to the ViewModels. Entities: UserEntity → represents swimmers. SwimTimeEntity → times linked to a user (1-to-many). Current Status The project works and syncs across devices. But there are two open concerns I’d like validated: Concurrency & Memory Safety Am I correctly separating viewContext (main/UI) vs. background context (used by CKSyncEngine)? Could there still be hidden risks of race conditions or memory crashes that I’m not catching? Swift 6 Sendable Compliance Currently, I still need @unchecked Sendable in the SyncEngine and repository layers. What is the recommended way to fully remove these workarounds and make the code safe under Swift 6’s stricter concurrency rules? Request Please review this sample project and confirm whether the concurrency model is correct. Suggest how I can remove the @unchecked Sendable annotations safely. Any additional code improvements or best practices would also be very welcome — the intention is to share this as a community resource. I believe once finalized, this could serve as a good reference demo for Core Data + CKSyncEngine + Swift 6, helping others migrate safely. Environment iOS 18.5 Xcode 16.4 macOS 15.6 Swift 6 Sample Project Here is the full sample project on GitHub: 👉 [https://github.com/jarnaez728/coredata-cksyncengine-swift6] Thanks a lot for your time and for any insights! Best regards, Javier Arnáez de Pedro
1
0
339
2w
How to access launchOptions in SceneDelegate?
Previously, when using AppDelegate, I was able to check the app’s launch options (launchOptions) to determine cases such as: Location updates (UIApplication.LaunchOptionsKey.location) Background push notifications (UIApplication.LaunchOptionsKey.remoteNotification) However, after migrating to the SceneDelegate approach, launchOptions is no longer available — it always returns nil. In my app, I need to branch the code depending on the launch options, but I can’t find a way to achieve this in the SceneDelegate environment. 👉 Is there a way to access launch options in SceneDelegate, similar to how it worked in AppDelegate? Or, if that’s no longer possible, what would be the proper alternative approach? Any guidance would be greatly appreciated.
2
0
107
2w