Hi, I have a project that uses SwiftUI, where we have a TabView, and in one of the tabs, I have a NavigationStack(path:). And created a logic to clear the NavigationStack path everytime you change to another Tab.
But found a bug, that if for some reason when doing a navigation in the NavigationStack, and rapidly tapping to another Tab, the NavigationStack doesn't gets clean up, or even if you have for some reason something allocated in the view you were navigation, doesn't get deinit if you have the logic for deinit a object when dismissing the view.
The environment I have is:
iPhone 12 Pro Max with iOS 17.6.1
This is the code that I have:
struct TabBarView: View {
@ObservedObject var tabBarVC = TabBarViewController()
var body: some View {
TabView(selection: $tabBarVC.selectedTab) {
Text("HomeView")
.tabItem {
Label("Home", systemImage: "house")
}
.tag(TabBarViewController.Tab.home)
SettingsView(settingsVC: tabBarVC.settingsVC)
.tabItem {
Label("Settings", systemImage: "gear")
}
.tag(TabBarViewController.Tab.settings)
}
.onChange(of: tabBarVC.selectedTab) { oldValue, newValue in
tabBarVC.settingsVC.clearNavigationPath()
}
}
}
class TabBarViewController: ObservableObject {
enum Tab {
case home
case settings
}
@Published var selectedTab: Tab = .home
@Published var settingsVC: SettingsViewController = .init()
}
class SettingsViewController: ObservableObject {
enum Destination {
case viewOne
case viewTwo
case viewThree
}
@Published var navigationPath: NavigationPath = .init()
func navigateTo(destination: Destination) {
self.navigationPath.append(destination)
}
func clearNavigationPath() {
self.navigationPath = .init()
}
}
The expected I am looking for is that everytime you change your tab, it cleans up the navigation stack, even if you change the tab when there is a navigation animation in process.
Swift
RSS for tagSwift is a powerful and intuitive programming language for Apple platforms and beyond.
Posts under Swift tag
200 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
I'm using Text(date, style: .timer) to display a timer in a WatchOS widget, which works great. The problem is that when the watchface goes dim the time goes from showing the time as "MM:SS" to showing "M minutes". Why is this occuring and how can I change the behavior? I understand it needs to remove seconds to preseve battery life, but why it is putting the word "minutes" at the end, this is messing up my layout. Thanks.
Hello.
I would like to ask for an assistance with testing AdAttributionKit flow that seems not working.
Goal: to close the AdAttributionKit logic flow loop starting from presenting and handling Ad in a publisher app and ending with receiving a postback request on my end point.
Problem: No postback request is received on my configured domain. It looks like AdAttributionKit cannot connect between AppImpression invocation in Publisher App and updating postback from the Advertised App, hence no update postback request are transmitted to my endpoint.
What was done:
Testing device
iPhone 13, iOS 18.0.1
Production Apple ID
AdAttributionKit Developer Mode is enabled
iPhone is reset and restarted
Publisher App
Test publisher application was created and configured (according to Apple's documentation [https://developer.apple.com/documentation/adattributionkit/configuring-a-publisher-app]) with the following:
AdNetworkIdentifiers item was added to app's Info.plist with number of Ad Network IDs. I tried to use in my tests (used below insted of the placeholder):
Registered SKAdNetwork Ad Network ID that ends with .skadnetwork
Not registered Ad Network ID that ends with .adattributionkit
JWS Impression was created with the following
JWS Header: {"kid" : "","alg" : "ES256"}
JWS Payload: {"impression-type" : "app-impression","impression-identifier" : "9547875E-C052-44CD-8CB9-193978CC5AB7", "timestamp" : 1729162517373,"publisher-item-identifier" : 0,"source-identifier" : 1111,"ad-network-identifier" : "","advertised-item-identifier" : 1125517808}
JWS Data: "BASE64(JWS-Header)"."BASE64(JWS-Payload)"."SIGNED("BASE64(JWS-Header).BASE64(JWS-Payload)")"
Signing was done with temporary key (created every time the JWS is composed) by the following:
let signingInput = "\(headerBase64String).\(payloadBase64String)"
let privateKey = Curve25519.Signing.PrivateKey()
var encodedSignature = ""
do {
let signature = try privateKey.signature(for: Data(signingInput.utf8))
encodedSignature = base64UrlEncode(signature)
} catch {
print("Error signing JWS: \(error.localizedDescription)")
}
UIEventAttributionView (with UITapGestureRecognizer) was added to my ViewController's main view and in a handling method of TAP event, AppImpression was created baased on JWS above and handleTap() method of this AppImpression instance was called.
AppImpression was tapped and AppStore has been launched (because to this moment no advertised app with was installed on a device):
attributionkitd Preflighting impression
AAKPubApp Connection established
attributionkitd Validated impression for advertised app: <MY-ADVERTISED-APP-APPSTORE-ID-PLACEHOLDER>
attributionkitd No distributor bundle ID received from app fetch
attributionkitd Distributor metadata cached for item ID <MY-ADVERTISED-APP-APPSTORE-ID-PLACEHOLDER>
attributionkitd Is anything happening?
attributionkitd Processing tap
attributionkitd Successfully validated publisher application
attributionkitd Successfully finalized click through impression
attributionkitd Impression is not eligible for re-engagement
attributionkitd Launching distributor for itemID: <MY-ADVERTISED-APP-APPSTORE-ID-PLACEHOLDER>
attributionkitd [0x70008b340] activating connection: mach=false listener=false peer=false name=(anonymous)
attributionkitd Distributor launch completed for item ID: <MY-ADVERTISED-APP-APPSTORE-ID-PLACEHOLDER>
Advertised App
Advertised App is an existing application on the AppStore. It was configured according Apple's documentation [https://developer.apple.com/documentation/adattributionkit/configuring-an-advertised-app].
AttributionCopyEndpoint key with my domain ("https://<MY_DOMAIN_PLACEHOLDER>.com") was added to app's Info.plist
EligibleForAdAttributionKitReengagementPostbackCopies key with "YES" value was added to Info.plist as well.
Number of postback method calls were added to the application in different places including application:didFinishLaunchingWithOptions.
Used AdAttributionKit method - (updateConversionValue(_:coarseConversionValue:lockPostback:)) [https://developer.apple.com/documentation/adattributionkit/postback/updateconversionvalue(_:coarseconversionvalue:lockpostback:)]
Application is written in Objective-C while using AdAttributionKit via Swift-to-ObjC regular bridging.
I tried to use Advertised App in the following ways:
To run it from Xcode. This way, when the advertised app is already installed, AppImpression tap in the publisher App doesn't recognize the Advertised App is installed and launches AppStore.
To install it from TestFlight. This way, AppImpression tap in the publisher App successfully recognizes the Advertised App is installed and launches it.
Both ways yield the same result - explanation below.
Advertised App launched - while calling update postback method in application:didFinishLaunchingWithOptions
attributionkitd Updating postback
attributionkitd Queueing update postback
attributionkitd [TXNf0dc] π Beginning transaction (Task runner: atomic)
attributionkitd Begin update postback
<MY-APPLICATION-NAME-PLACEHOLDER> Connection established
attributionkitd [TXN5421] π Ending transaction (<private>) (<private>)
attributionkitd Retrieved conversion window thresholds: <private>
attributionkitd [TXNf0dc] π Ending transaction (<private>) (<private>)
...
attributionkitd Calling launch handler for com.apple.attributionkitd.development-postback-transmission
attributionkitd Begin task for identifier: com.apple.attributionkitd.development-postback-transmission
attributionkitd Running barktivity: com.apple.attributionkitd.development-postback-transmission
attributionkitd [TXN46f0] π Beginning transaction (<private>)
attributionkitd Found 0 postbacks eligible for transmission for environments: <private>
attributionkitd Postback transmission completed
attributionkitd [TXN46f0] π Ending transaction (<private>) (<private>)
attributionkitd Marking task <BGRepeatingSystemTask: com.apple.attributionkitd.development-postback-transmission> complete
attributionkitd Task completed for identifier: com.apple.attributionkitd.development-postback-transmission
The problem I can see here is in the following line:
attributionkitd Found 0 postbacks eligible for transmission for environments: <private>
It looks like AdAttributionKit cannot connect between AppImpression invocation in Publisher App and updating postback from the Advertised App.
Please correct me in case I'm doing anything wrong or missing anything.
Thank you very much.
On first installation of the sample app of iMessage Extension from apple
the app icon visible, but after I uninstalled it and again installed the app, the app icon is not visible. Here is the screenshot and the apple sample app.
https://developer.apple.com/documentation/messages/icecreambuilder-building-an-imessage-extension
Hello,
I'm working with the Network framework in Swift and have encountered an issue when attempting to create multiple NWListener instances on the same port. I am specifically trying to set the allowLocalEndpointReuse property on the NWParameters used for both listeners, but it seems that even with this property set, the second listener fails to start.
Hereβs a simplified version of my implementation:
import Foundation
import Network
class UDPServer {
private var listener1: NWListener?
private var listener2: NWListener?
private let port: NWEndpoint.Port
init(port: UInt16) {
self.port = NWEndpoint.Port(rawValue: port) ?? NWEndpoint.Port(45000)
startListeners()
}
private func startListeners() {
let udpOptions = NWProtocolUDP.Options()
let params = NWParameters(udp: udpOptions)
params.allowLocalEndpointReuse = true
// Create first listener
do {
listener1 = try NWListener(using: params, on: port)
listener1?.start(queue: .global())
} catch {
print("Failed to create Listener 1: \(error)")
}
// Create second listener
do {
listener2 = try NWListener(using: params, on: port)
listener2?.start(queue: .global())
} catch {
print("Failed to create Listener 2: \(error)")
}
}
}
// Usage example
let udpServer = UDPServer(port: 45000)
RunLoop.main.run()
Observations:
I expect both listeners to operate without issues since I set allowLocalEndpointReuse to true.
However, when I attempt to start the second listener on the same port, it fails with an error.
output
nw_path_evaluator_evaluate NECP_CLIENT_ACTION_ADD error [48: Address already in use]
nw_path_create_evaluator_for_listener nw_path_evaluator_evaluate failed
nw_listener_start_on_queue [L2] nw_path_create_evaluator_for_listener failed
Listener 1 ready on port 45000
Listener 2 failed: POSIXErrorCode(rawValue: 48): Address already in use
Listener 2 cancelled
Questions:
Is there a limitation in the Network framework regarding multiple listeners on the same port even with allowLocalEndpointReuse?
Should I be using separate NWParameters for each listener, or is it acceptable to reuse them?
Even when trying to initialize NWParameters with NWProtocolUDP.Options, it doesn't seem to change anything. What steps should I take to modify these properties effectively?
If I wanted to set the noDelay option for TCP, how would I do that? Even when initializing NWParameters with init(.tls: , .tcp:), it doesn't seem to have any effect.
Any insights or recommendations would be greatly appreciated!
Thank you!
I'm developing two native apps and one is a authentication app and other one is business app. In the main flow if buisness application is on the foreground and did nothing for at least 10 minutes it will automatically time out and redirect to the autentication app for token refresh. In this flow universal link redirect to the authetication app without opening Safari.
But if i execute the below flow buissness app redirect to the Safari.
Buisness App In Foregorund β Displaying a OS screen while app is in Foreground(Like Push Notification Center) β On this satate leave device for 10 minutes β Buisness app will automatically timeout and rediret to Safari(In safari γNoSuchKey The specified key does not exist.γmessage is displaying but authentication app Universal link Start button is showing) β After click the Universal Link start button in Safari Authentication App open.
I use the below code to start the Universal Link:
if let url = URL(string: path) {
UIApplication.shared.open(url)
}
So i would like to know is there a special reason that when Displaying a OS screen while app is in Foreground(Like Push Notification Center) affect the normal flow of Universal redirection to another app?
I'm trying to setup my view so that there's (in order from top of display to bottom) a VStack with some content, followed by a List, followed by another VStack with a couple buttons where progressive blurs separate the list and the two VStack's content. Now, in the current version of my app when the user scrolls up or down, the list just cuts off. I'm having a very difficult time maintaining the entire view's vertical positioning while adding these blurs with ZStack. The code below is the current implementation with an attempted progressive blur. Right now, it's close, but the list is acting exactly how I don't want it - anchoring to the top of the display (its natural position) and causes the toolbar to blur when scrolled under (I can't disable toolbar without losing my toolbarItems either). Any help is appreciated.
NavigationStack {
VStack {
ZStack {
List(filteredItems) { item in
NavigationLink(destination: ItemDetailView(item: item)) {
HStack(spacing: 15) {
Image(systemName: item.icon)
VStack(alignment: .leading) {
Text(item.name)
Text("")
}
.multilineTextAlignment(.leading)
}
.padding(.vertical, 5)
}
}
.scrollIndicators(.hidden)
.scrollContentBackground(.hidden)
VStack(spacing: 5) {
if #available(iOS 18.0, *) {
Image(systemName: "plus.square.on.square.fill")
.resizable()
.scaledToFit()
.frame(maxHeight: 50)
.symbolEffect(.bounce.up, options: .nonRepeating)
} else {
Image(systemName: "plus.square.on.square.fill")
.resizable()
.scaledToFit()
.frame(maxHeight: 50)
}
Text("Items")
.font(.largeTitle.bold())
Text("Create, View, and Manage Your Items")
.font(.system(size: 12).weight(.bold))
.multilineTextAlignment(.center)
ScrollView(.horizontal) {
HStack(spacing: 20) {
filterButton(icon: "car.fill", color: .red, label: "Auto")
filterButton(icon: "cart.fill", color: .purple, label: "Shopping")
filterButton(icon: "laptopcomputer", color: .blue, label: "Tech")
filterButton(icon: "airplane", color: .orange, label: "Travel")
filterButton(icon: "gamecontroller.fill", color: .green, label: "Entertainment")
}
.padding(.leading, 25)
}
.scrollBounceBehavior(.basedOnSize)
.scrollIndicators(.hidden)
Spacer()
}
.padding(.top)
VStack {
Rectangle()
.fill(.thinMaterial)
.frame(height: 300)
.mask {
VStack(spacing: 0) {
LinearGradient(colors: [Color.black.opacity(0),
Color.black.opacity(0.383),
Color.black.opacity(0.707),
Color.black.opacity(0.924),
Color.black],
startPoint: .bottom,
endPoint: .top)
.frame(height: 400)
Rectangle()
}
}
Spacer()
}
.ignoresSafeArea()
VStack {
Spacer()
Rectangle()
.fill(.thinMaterial)
.frame(height: 200)
.mask {
VStack(spacing: 0) {
LinearGradient(colors: [Color.black.opacity(0),
Color.black.opacity(0.383),
Color.black.opacity(0.707),
Color.black.opacity(0.924),
Color.black],
startPoint: .top,
endPoint: .bottom)
.frame(height: 100)
Rectangle()
}
}
}
.ignoresSafeArea()
VStack(spacing: 12) {
Spacer()
Button {
showingAddItemView.toggle()
} label: {
HStack {
Image(systemName: "plus.circle")
Spacer()
.frame(width: 7)
Text("New Item")
.padding(.trailing, 3)
}
#if os(visionOS)
.padding(.vertical)
#endif
}
.padding(10)
#if os(iOS)
.background {
Capsule()
}
#endif
NavigationLink("Continue") {
}
}
.padding()
underlying Objective-C module 'FirebaseSharedSwift' not found
aymodazhnyneylcscdggrsgjocui/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FirebaseSharedSwift.build/Objects-normal/x86_64/FirebaseSharedSwift.private.swiftinterface:5:19: underlying Objective-C module 'FirebaseSharedSwift' not found
Command SwiftCompile failed with a nonzero exit code
The code below is a simplified form of part of my code for my Swift Package Manager, Swift 5.6.1, PromiseKit 6.22.1, macOS command-line executable.
It accepts a Mac App Store app ID as the sole argument. If the argument corresponds to an app ID for an app that was installed from the Mac App Store onto your computer, the executable obtains some information from Spotlight via a NSMetadataQuery, then prints it to stdout.
I was only able to get the threading to work by calling RunLoop.main.run(). The only way I was able to allow the executable to return instead of being stuck forever on RunLoop.main.run() was to call exit(0) in the closure passed to Promise.done().
The exit(0) causes problems for testing. How can I allow the executable to exit without explicitly calling exit(0), and how can I improve the threading overall?
I cannot currently use Swift Concurrency (await/async/TaskGroup) because the executable must support macOS versions that don't support Swift Concurrency. A Swift Concurrency solution variant would be useful as additional info, though, because, sometime in the future, I might be able to drop support for macOS versions older than 10.15.
Thanks for any help.
import Foundation
import PromiseKit
guard CommandLine.arguments.count > 1 else {
print("Missing adamID argument")
exit(1)
}
guard let adamID = UInt64(CommandLine.arguments[1]) else {
print("adamID argument must be a UInt64")
exit(2)
}
_ = appInfo(forAdamID: adamID)
.done { appInfo in
if let jsonData = try? JSONSerialization.data(withJSONObject: appInfo),
let jsonString = String(data: jsonData, encoding: .utf8)
{
print(jsonString.replacingOccurrences(of: "\\/", with: "/"))
}
exit(0)
}
RunLoop.main.run()
func appInfo(forAdamID adamID: UInt64) -> Promise<[String: Any]> {
Promise { seal in
let query = NSMetadataQuery()
query.predicate = NSPredicate(format: "kMDItemAppStoreAdamID == %d", adamID)
query.searchScopes = ["/Applications"]
var observer: NSObjectProtocol?
observer = NotificationCenter.default.addObserver(
forName: NSNotification.Name.NSMetadataQueryDidFinishGathering,
object: query,
queue: .main
) { _ in
query.stop()
defer {
if let observer {
NotificationCenter.default.removeObserver(observer)
}
}
var appInfo: [String: Any] = [:]
for result in query.results {
if let result = result as? NSMetadataItem {
var attributes = ["kMDItemPath"]
attributes.append(contentsOf: result.attributes)
for attribute in attributes {
let value = result.value(forAttribute: attribute)
switch value {
case let date as Date:
appInfo[attribute] = ISO8601DateFormatter().string(from: date)
default:
appInfo[attribute] = value
}
}
}
}
seal.fulfill(appInfo)
}
DispatchQueue.main.async {
query.start()
}
}
}
Can we access a Vision pro's spatial persona in application's view without using SharePlay or group activity like any other 3d Avatar?
I want to use that persona in app and without live rendering I just want to pass some voice commands like Avatar is speaking.
We started building our project in XCode 16 only to find a super weird crash that was 100% reproducible.
I couldn't really understand why it was crashing, so I tried to trim down the problematic piece of code to something that I could provide in a side project. The actual piece of code crashing for us is significantly different, but this small example showcases the crash as well.
https://github.com/Elih96/XCode16CrashReproducer
our observation is, that this combination of async let usage + struct structure leads to a SIGABRT crash in the concurrency library.
In both the main project and the example project, moving away from async let and using any other concurrency mechanism fixes the crash.
This was reproducible only on Xcode 16 with iOS 15 set as minimum deployment for the target. It works fine on Xcode 15, and if we bump the min deployment to 16 on Xcode 16, it also runs fine. I've attached a small project that reproduces the error.
I'm sure I didn't provide the ideal reproduction scenario, but that's what I managed to trim it down to. Making random changes such as removing some properties from the B struct or remove the:
let _ = A().arrayItems.map { _ in "123" }
will stop the crash from happening, so I just stopped making changes.
The stack trace from the crash:
frame #0: 0x00000001036d1008 libsystem_kernel.dylib`__pthread_kill + 8
frame #1: 0x0000000102ecf408 libsystem_pthread.dylib`pthread_kill + 256
frame #2: 0x00000001801655c0 libsystem_c.dylib`abort + 104
frame #3: 0x000000020a8b7de0 libswift_Concurrency.dylib`swift::swift_Concurrency_fatalErrorv(unsigned int, char const*, char*) + 28
frame #4: 0x000000020a8b7dfc libswift_Concurrency.dylib`swift::swift_Concurrency_fatalError(unsigned int, char const*, ...) + 28
frame #5: 0x000000020a8baf54 libswift_Concurrency.dylib`swift_task_dealloc + 124
frame #6: 0x000000020a8b72c8 libswift_Concurrency.dylib`asyncLet_finish_after_task_completion(swift::AsyncContext*, swift::AsyncLet*, void (swift::AsyncContext* swift_async_context) swiftasynccall*, swift::AsyncContext*, void*) + 72
* frame #7: 0x000000010344e6e4 CrashReproducer.debug.dylib`closure #1 in closure #1 in CrashReproducerApp.body.getter at CrashReproducerApp.swift:17:46
frame #8: 0x00000001cca0a560 SwiftUI`___lldb_unnamed_symbol158883
frame #9: 0x00000001cca09fc0 SwiftUI`___lldb_unnamed_symbol158825
frame #10: 0x00000001cca063a0 SwiftUI`___lldb_unnamed_symbol158636
frame #11: 0x00000001cca09268 SwiftUI`___lldb_unnamed_symbol158726
Hi,
I'm using NSPanel that his level is .popUpMenu and when I use .quickLookPreview in SwiftUI it make the the Quick Look behind the nspanel how can I fix it without change the level of NSPanel?
I'm experiencing issues with the Core ML Async API, as it doesn't seem to be working correctly. It consistently hangs during the
"03 performInference, after get smallInput, before prediction" part,
as shown in the attached:
log1.txt
log2.txt
Below is my code. Could you please advise on how I should modify it?
private func createFrameAsync(for sampleBuffer: CMSampleBuffer ) {
guard let pixelBuffer = sampleBuffer.imageBuffer else { return }
Task {
print("**** createFrameAsync before performInference")
do {
try await runModelAsync(on: pixelBuffer)
} catch {
print("Error processing frame: \(error)")
}
print("**** createFrameAsync after performInference")
}
}
func runModelAsync(on pixelbuffer: CVPixelBuffer) async
{
print("01 performInference, before resizeFrame")
guard let data = metalResizeFrame(sourcePixelFrame: pixelbuffer, targetSize: MTLSize.init(width: InputWidth, height: InputHeight, depth: 1), resizeMode: .scaleToFill) else {
os_log("Preprocessing failed", type: .error)
return
}
print("02 performInference, after resizeFrame, before get smallInput")
let input = model_smallInput(input: data)
print("03 performInference, after get smallInput, before prediction")
if let prediction = try? await mlmodel!.model.prediction(from: input) {
print("04 performInference, after prediction, before get result")
var results: [Float] = []
let output = prediction.featureValue(for: "output")?.multiArrayValue
if let bufferPointer = try? UnsafeBufferPointer<Float>(output!) {
results = Array(bufferPointer)
}
print("05 performInference, after get result, before setRenderData")
let localResults = results
await MainActor.run {
ScreenRecorder.shared
.setRenderDataNormalized(
screenImage: pixelbuffer,
depthData: localResults
)
}
print("06 performInference, after setRenderData")
}
}
Hello, I am currently developing an application using SensorKit to retrieve visit data. While the data retrieval works smoothly on one iPhone (iPhone 14, iOS 18.0.1), it fails on other devices, including:
iPhone 15 Pro Max with iOS 18.1 Beta
Another iPhone 14 with iOS 18.0
Iβve verified that the entitlements are configured properly, and the app has the necessary SensorKit visit permissions across all devices. Despite these steps, only one of the phones is able to retrieve the visit data correctly.
Is there any minimum hardware requirement or compatibility issue with certain models or configurations that I should be aware of for using SensorKit visits?
Any guidance or insight would be greatly appreciated!
Thank you.
Is this Relationship correct? Does this cause a circular reference? This runs on 18 but crashes on 17 in the swift data internals.
@Model
final class Item {
@Attribute(.unique) var id: UUID
var date: Date
@Relationship(deleteRule: .nullify, inverse: \Summary.item) var summary: Summary?
init(date: Date = Date.now) {
self.id = UUID()
self.date = Calendar.current.startOfDay(for: date)
self.summary = Summary(self)
}
}
@Model
final class Summary {
@Attribute(.unique) var id = UUID()
@Relationship var item: Item?
init(_ item: Item) {
self.item = item
}
}
I want to simulate the pressing of Fn (Globe) + Control + arrow keys combo, but Iβm encountering an issue where the Fn modifier seems to be ignored, and the system behaves as if only Control + arrow keys are pressed.
In macOS, the combination of Fn + Right Arrow (key code 124) is treated as End (key code 119), and even that didnβt have expected behavior. Instead of moving the window to the right edge of the screen on Sequoia, it switches to the next space, which is the default behavior for Control + Right Arrow.
Demo:
(I included Fn + Control + C to show that centering the window works for example.)
import SwiftUI
@main
struct LittleKeypressDemo: App {
var body: some Scene {
Window("Keypress Demo", id: "keypress-demo") {
ContentView()
}
.windowStyle(.hiddenTitleBar)
.windowResizability(.contentSize)
.windowBackgroundDragBehavior(.enabled)
}
}
struct ContentView: View {
var body: some View {
VStack(spacing: 20) {
KeyPressButton(icon: "arrowtriangle.right.fill", keyCode: 124)
KeyPressButton(icon: "arrow.down.to.line", keyCode: 119)
KeyPressButton(label: "C", keyCode: 8)
}
.padding()
}
}
struct KeyPressButton: View {
let icon: String?
let label: String?
let keyCode: CGKeyCode
init(icon: String? = nil, label: String? = nil, keyCode: CGKeyCode) {
self.icon = icon
self.label = label
self.keyCode = keyCode
}
var body: some View {
Button(action: { simulateKeyPress(keyCode) }) {
HStack {
Image(systemName: "globe")
Image(systemName: "control")
if let icon = icon {
Image(systemName: icon)
} else if let label = label {
Text(label)
}
}
}
.buttonStyle(.bordered)
.controlSize(.large)
}
}
func simulateKeyPress(_ keyCode: CGKeyCode) {
let fnKey = VirtualKey(keyCode: 63, flags: .maskSecondaryFn)
let controlKey = VirtualKey(keyCode: 59, flags: [.maskControl, .maskSecondaryFn])
let targetKey = VirtualKey(keyCode: keyCode, flags: [.maskControl, .maskSecondaryFn])
[fnKey, controlKey, targetKey].forEach { $0.pressAndRelease() }
}
struct VirtualKey {
let keyCode: CGKeyCode
let flags: CGEventFlags
func pressAndRelease() {
postKeyEvent(keyDown: true)
postKeyEvent(keyDown: false)
}
private func postKeyEvent(keyDown: Bool) {
guard let event = CGEvent(keyboardEventSource: nil, virtualKey: keyCode, keyDown: keyDown) else { return }
event.flags = flags
event.post(tap: .cghidEventTap)
}
}
Expected behavior:
Simulating the key combo Fn + Control + Right Arrow on macOS Sequoia should move the current window to the right half of the screen, instead of switching to the next desktop space.
Questions:
Is CGEventFlags.maskSecondaryFn enough to simulate the Fn key in combination with Control and the arrow keys? Are there alternative approaches or workarounds to correctly simulate this behavior? Whatβs the obvious thing I missing?
(Btw., window management is completely irrelevant here. Iβm specifically asking about simulating these key presses.)
Any insights or suggestions would be greatly appreciated.
Thank you.
I Use Angular/Ionic and none matter with Android.
But with IOS, it's very complicated.
I Use Xcode CLoud, but I have this error :
Unable to open base configuration reference file '/Volumes/workspace/repository/ios/App/Pods/Target Support Files/Pods-App/Pods-App.release.xcconfig'.
App.xcodeproj:1
I don't know this path : /Volumes/workspace/repository and I don't know why Xcode cloud use it..
I have on my local : nameApp//ios/App/Pods/Target Support Files/Pods-App/Pods-App.release.xcconfig'.
I need your help please, already 1 month I've been on it just to succeed in building on ios
The Problem
My team has recently discovered a problem in one of our macOS apps. It uses SwiftUI and Combine, as it still needs to support macOS 13.
It uses a NavigationSplitView to display a sidebar-detail UI.
On macOS 15, we started running into a bug: When selecting an item from the sidebar, the corresponding detail does not initially show up, and a detail page shows up only when selecting a second item from the sidebar. The following message would be printed into Xcode's console:
Publishing changes from within view updates is not allowed, this will cause undefined behavior.
This message would only get printed into the console, and would not be attached to any specific line.
Oftentimes, selecting a subsequent item from the sidebar also either completely clears the detail page, doesn't do anything, and there was a crash reported as well.
The app is compiled using Xcode 16.0.
Architecture Overview
The app uses NavigationSplitView with multiple different detail pages. .id is attached to the detail view in its corresponding NavigationLink, which used to properly show the corresponding detail page.
The ID is stored in an observable AppState, which uses Combine's ObservableObject in the production app, and Observation's Observable in the minimal example.
Example Code
Minimal Reproductible Example
You can see a minimal reproducible example here: https://github.com/buresdv/Navigation-Problems
This example also features a debug field at the end of the sidebar, called "navigationSelection". When clicking one of the items, the ID gets correctly set, but the detail page does not update.
Production App
The production app is a bit more complex, but the core system is the same.
For complete code, see:
https://github.com/buresdv/Cork
Some relevant lines include the navigation root, sidebar list, and the navigation links
Notes
We were able to reproduce these issues on multiple user systems
This issue seems to have started occuring when we updated to macOS 15
At the same time, we updated the app to Strict Concurrency Checking and Swift 6, although we did not change anything in the navigation system
I use Kotlin Multiplayer Development to develop iOS applications. I access the methods in the Kotlin class of the shared module in the ContentView.swift file. Functions without parameters can be used normally, but functions with parameters cannot. For example, the 78th line of code on the left side of the screenshot works, but the 79th line does not. Can someone please tell me the reason? Thank you!
Can vector embeddings be used in a SwiftData Model?
If yes, are there resources available to learn more about it? or at least a guided step on how to make it work?