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

Posts under Swift tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Right bar button items in iOS 26 visual presentation
I have attached two images of two screens below. In one screen, bar button are enclosed within separate, distinct, rounded-rectangle 'liquid glass' capsules. In other screen, bar buttons are enclosed within separate, distinct, rounded-rectangle "liquid glass" capsules. They are not visually merged into one larger capsule. Both are having same code. But why it is not same ?
1
0
90
Jul ’25
Large title is not visible in iOS 26
I am using below code to change navigationBar bg colour, but the text is hidden in large title. It works fine in previous versions. Kindly refer below code and attached images. Code: override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.prefersLargeTitles = true navigationItem.largeTitleDisplayMode = .always let appearance = UINavigationBarAppearance() appearance.backgroundColor = UIColor( red: 0.101961, green: 0.439216, blue: 0.388235, alpha: 1.0 ) navigationController?.navigationBar.standardAppearance = appearance navigationController?.navigationBar.scrollEdgeAppearance = appearance navigationController?.navigationBar.compactAppearance = appearance } Referenced images:
1
1
175
Aug ’25
Positioning an image
This may seem really basic, but I'm not using the screen designer, I'm doing this old school (programmatically). I think I'm using Swift 5 (not actually sure). This image may help. So I created my own UIImageView class called GenericImage class GenericImage: UIImageView, @unchecked Sendable { ... } I create the GenericImage class and add it to the View Controller. Then I load the image and set some positioning within my GenericImage class let imageView = GenericImage(frame: CGRect.zero) self.view.addSubview(imageView) imageView.processResponse(componentDictionary ) In the GenericImage class I load the image and set some constraints. self.imageFromURL(urlString: imageUrl) self.translatesAutoresizingMaskIntoConstraints = false self.contentMode = .scaleAspectFit self.widthAnchor.constraint(equalToConstant: 100.0).isActive = true self.heightAnchor.constraint(equalToConstant: 100.0).isActive = true self.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true self.topAnchor.constraint(equalTo: self.centerYAnchor).isActive = true The image is displayed at the top left of the screen. I'm guessing that the code I have written should center the image on the screen. However, while I would like to know how to center the image, I also want to be able to position it at a specific place on the screen, using points (or pixels). Any suggestions?
3
0
111
Jul ’25
Liquid Glass Error
Hello everyone. I'm getting an error in my code and I don't know why. Can someone explain it to me? import SwiftUI struct ContentView: View{ var body: some View{ VStack { Button {} label: { Text("Click Me") } .buttonStyle(.glass) .frame(width: 200, height: 200) } } } The error is as follows: Reference to member 'glass' cannot be resolved without a contextual type Thanks for your help
1
0
193
Jul ’25
Getting two searchBar in iOS 26.0
Hi team, while i am using below code, i am getting two searchBar at top & bottom. Kindly refer below code & attached image Code: override func viewDidLoad() { super.viewDidLoad() title = "Test Data" setupSearchData() DispatchQueue.main.asyncAfter(deadline: .now() + 2) { self.setupSearchData() } } func setupSearchData() { navigationController?.navigationBar.prefersLargeTitles = false let searchController = UISearchController(searchResultsController: nil) navigationItem.searchController = searchController } It is working fine for other iOS versions. In my real useCase, i will refresh screen after API completed, then this issue occurred in my app.
2
0
83
Jul ’25
Cannot find 'atomic_flag' in scope in Xcode 26
Hi, In Xcode 16.4, the atomic_flag() method can be used, but in Xcode 26.0, it is not available. An error message saying Cannot find 'atomic_flag' in scope is displayed. This can be reproduced simply by trying to use atomic_flag() in a newly created empty project. Thank you. Xcode: Version 26.0 beta 4 (17A5285i), macOS: 15.5(24F74) import SwiftUI struct ContentView: View { var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") } .padding() .task { _ = atomic_flag() } } }
1
1
100
Aug ’25
Getting FoundationsModel running in Simulator
I have a mac (M4, MacBook Pro) running Tahoe 26.0 beta. I am running Xcode beta. I can run code that uses the LLM in a #Preview { }. But when I try to run the same code in the simulator, I get the 'device not ready' error and I see the following in the Settings app. Is there anything I can do to get the simulator to past this point and allowing me to test on it with Apple's LLM?
3
0
313
Jul ’25
Windows-specific timeout issue with URLSession in Swift (Error Code -1001)
Hello everyone, 👋🏼🤠 I've been struggling with a persistent issue for several weeks and would greatly appreciate any insights or suggestions from the community. ❗️Problem Summary We are sending JSON requests (~100 KB in size) via URLSession from a Swift app running on Windows. These requests consistently time out after a while. Specifically, we receive the following error: Error Domain=NSURLErrorDomain Code=-1001 "(null)" This only occurs on Windows – under macOS and Linux, the same requests work perfectly. 🔍 Details The server responds in under 5 seconds, and we have verified that the backend (a Vapor app in Kubernetes) is definitely not the bottleneck. The request always hits the timeout interval, no matter how high we configure it: 60, 120, 300, 600 seconds – the error remains the same. (timeoutForRequest) The request flow: Swift App (Windows) ---> HTTPS ---> Load Balancer (NGINX) ---> HTTP ---> Ingress Controller ---> Vapor App (Kubernetes) On the load balancer we see this error: client prematurely closed connection, so upstream connection is closed too (104: Connection reset by peer) The Ingress Controller never receives the complete body in these error cases. The content length set by the Swift app exceeds the data actually received. We disabled request buffering in the Ingress Controller, but the issue persists. We even tested a setup where we inserted a Caddy server in between to strip away TLS. The Swift app sent unencrypted HTTP requests to Caddy, which then forwarded them. This slightly improved stability but did not solve the issue. 🧪 Additional Notes The URLSession is configured in an actor, with a nonisolated URLSession instance: actor DataConnectActor { nonisolated let session : URLSession = URLSession(configuration: { let urlSessionConfiguration : URLSessionConfiguration = URLSessionConfiguration.default urlSessionConfiguration.httpMaximumConnectionsPerHost = ProcessInfo.processInfo.environment["DATACONNECT_MAX_CONNECTIONS"]?.asInt() ?? 16 urlSessionConfiguration.timeoutIntervalForRequest = TimeInterval(ProcessInfo.processInfo.environment["DATACONNECT_REQUEST_TIMEOUT"]?.asInt() ?? 120) urlSessionConfiguration.timeoutIntervalForResource = TimeInterval(ProcessInfo.processInfo.environment["DATACONNECT_RESSOURCE_TIMEOUT"]?.asInt() ?? 300) urlSessionConfiguration.httpAdditionalHeaders = ["User-Agent": "DataConnect Agent (\(Environment.version))"] return urlSessionConfiguration }()) public internal(set) var accessToken: UUID? = nil ... } Requests are sent via a TaskGroup, limited to 5 concurrent tasks. The more concurrent tasks we allow, the faster the timeout occurs. We already increased the number of ephemeral ports in Windows. This made things slightly better, but the problem remains. Using URLSessionDebugLibcurl=1 doesn't reveal any obvious issue related to libcurl. We have also implemented a retry mechanism, but all retries also time out. 🔧 Request Flow (Code Snippet Summary) let data = try JSONEncoder().encode(entries) var request = URLRequest(url: url) request.httpMethod = "POST" request.httpBody = data request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type") // additional headers... let (responseData, response) = try await urlSession.data(for: request) ✅ What We’ve Tried Tested with and without TLS Increased timeout and connection settings Disabled buffering on Ingress Increased ephemeral ports on Windows Limited concurrent requests Used URLSessionDebugLibcurl=1 We don't know how we can look any further here. Thank you in advance for any guidance!
2
0
175
Jul ’25
TabView + NavigationStack + ScrollView navigationTitle bug
Hello there! I've been struggline with this thing for a two days now, and seems like it's a bug in SwiftUI. Navigation title is jumping on top of the ScrollView's content when switching tabs in TabView. Steps to reproduce: Scroll one tab to the bottom so that the large title is hidden and the floating toolbar appears. Go to another tab in the tab bar. Go back to the initial tab (it is still scrolled), and press the current tab button again to scroll to the top. The navigation title will glitch and be on top of the content. The animation fixes if you scroll again manually. Video: https://share.cleanshot.com/PFCSKMlH Code (simplified): import SwiftData import SwiftUI @main struct MyApp: App { var body: some Scene { WindowGroup { TabsContentView() } } } // ... struct TabsContentView: View { enum Tab { case library, profile } @State private var selectedTab: Tab = .library var body: some View { TabView(selection: $selectedTab) { NavigationStack { YourLibraryList() .navigationTitle("Your Library") } .tabItem { Label("Library", systemImage: "tray.fill") } .tag(Tab.library) NavigationStack { VStack { Spacer() Text("Profile") .font(.largeTitle) .foregroundColor(Color.theme.text) Text("Manage your account and preferences here") .font(.body) .foregroundColor(Color.theme.mutedForeground) .multilineTextAlignment(.center) .padding(.horizontal) Spacer() } .navigationTitle("Explore") } .tabItem { Label("Profile", systemImage: "person.fill") } .tag(Tab.profile) } .toolbarBackground(.ultraThinMaterial, for: .tabBar) .toolbarBackground(.visible, for: .tabBar) } } // ... struct YourLibraryList: View { var body: some View { ScrollView { VStack(spacing: 12) { ForEach(1 ... 20, id: \.self) { number in RoundedRectangle(cornerRadius: 12) .fill(Color.blue.opacity(0.1)) .stroke(Color.blue, lineWidth: 1) .frame(height: 60) .overlay( Text("\(number)") .font(.title2) .fontWeight(.semibold) .foregroundColor(.blue) ) } } .padding(.horizontal) } } }
2
0
190
Jul ’25
Why does converting HEIC/HEIF to JPEG using UIImage.jpegData(compressionQuality: 1.0) significantly increase file size?
I'm working with images selected from the iOS Photos app using PHPickerViewController. Some images appear as HEIF in the Photos info panel — which I understand are stored in the HEIC format, i.e., HEIF containers with HEVC-compressed images, commonly used on iOS when "High Efficiency" is enabled. To convert these images to JPEG, I'm using the standard UIKit approach: if let image = UIImage(data: heicData) { let jpegData = image.jpegData(compressionQuality: 1.0) } However, I’ve noticed that this conversion often increases the image size significantly: Original HEIC/HEIF: ~3 MB Converted JPEG (quality: 1.0): ~8–12 MB There’s no resolution change or image editing — it’s just a direct conversion. I understand that HEIC is more efficient than JPEG, but the increase in file size feels disproportionate. Is this kind of jump expected, or are there any recommended workarounds to avoid it?
1
0
120
Jul ’25
Main actor-isolated property can not be referenced
Hello I'm getting this error in my code and I don't know why. Can somebody explain this or point me at a help article. import UIKit var greeting = "Hello, playground" let imageView = UIImageView() imageView.image = UIImage(named: "image") Utils.getImageSize(view: imageView) class Utils { static func getImageSize(view imageView: UIImageView) { let image = imageView.image print("Image size = \(image?.size ?? CGSize.zero)") } } The error is as follows: Cheers Murray
4
0
127
Jul ’25
Image cropping
Currently, I’m working on developing a small macOS utility tool for my photography. In my camera, I have a digital zoom feature. I prefer using this feature when I shoot both JPEG and DNG files. While the JPEG is already cropped to the desired format, the DNG file contains metadata (DefaultUserCrop: 0.22, 0.22, 0.78, 0.78). For instance, when I open that DNG file in Lightroom, it pre-crops the image non-destructively. However, I prefer using Pixelmator Pro for editing. Unfortunately, Pixelmator Pro doesn’t have this feature. So, I thought I could create an app that allows me to pre-crop the image for editing in Pixelmator Pro afterward. Does someone have a better idea or some hints on how I could solve it?
1
0
168
Jul ’25
"The compiler is unable to type-check this expression..."
"/Users/rich/Work/IdeaBlitz/IdeaBlitz/IdeaListView.swift:30:25 The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions" Is it just me? I get this on syntax errors, missing commas, missing quotes, and for no particular reason at all that I can see. I don't think I've been able to write a single, simple, SwiftUI view without seeing this multiple times. "Breaking it up" just makes it harder to read. Simple, inline, 2-page views become 8-page, totally unreadable, monstrosities. Am I doing something wrong? Or is this just the state of SwiftUI today? Or is there some way to tell the compiler to take more time on this expression? I mean, if these can be broken up automatically, then why doesn't the compiler to that already?
2
0
162
Jul ’25
Unable to see *any* debug statements from the FileProviderExtension spawned from Finder
I am in the process of writing a macOS app using NSFileProviderExtension so that I can map my customer's data in Finder. I am in the process of building it out, I had initially started in Obj-C and then after the advice of folks here (https://developer.apple.com/forums//thread/793272?answerId=849339022&page=1#849752022) I have switched to Swift as the NSReplicatedFileProvider is not available in Obj-C. I have done the main app and also started plugging away with the FileProviderExtension. To verify that I have properly setup, I create a static list of files in the FileProviderExtension enumerate so I can see it work in Finder. I build the app and it works as expected and I see it mounted in Finder and I see the static list of files. But what I don't see is any debug statements in the app, none of those message show up in the logs. I am baffled by this. I check the log stream to see what the process prints out and I know it is logging everything else eg: 2025-07-18 11:32:05.772364-0700 0x19ea3f9 Activity 0x1172100 63622 0 DriveFileProviderExtension: (libsystem_secinit.dylib) AppSandbox 2025-07-18 11:32:05.794609-0700 0x19ea3f9 Activity 0x1172101 63622 0 DriveFileProviderExtension: (libsystem_info.dylib) Retrieve User by ID 2025-07-18 11:32:05.800179-0700 0x19ea3f9 Default 0x0 63622 0 DriveFileProviderExtension: (ExtensionFoundation) [com.apple.extensionkit:default] Extension `/Users/radwar/Library/Developer/Xcode/DerivedData/Drive-fxfhbjutfvumoabnnfmxxstpifha/Build/Products/Debug/Drive.app/Contents/PlugIns/DriveFileProviderExtension.appex/Contents/MacOS/DriveFileProviderExtension` of type: `1` launched. 2025-07-18 11:32:05.801453-0700 0x19ea3f9 Default 0x0 63622 0 DriveFileProviderExtension: (RunningBoardServices) [com.apple.runningboard:connection] Initializing connection 2025-07-18 11:32:05.803083-0700 0x19ea3f9 Default 0x0 63622 0 DriveFileProviderExtension: (RunningBoardServices) [com.apple.runningboard:process] Removing all cached process handles 2025-07-18 11:32:05.803231-0700 0x19ea613 Default 0x0 63622 0 DriveFileProviderExtension: (RunningBoardServices) [com.apple.runningboard:connection] Sending handshake request attempt #1 to server 2025-07-18 11:32:05.803414-0700 0x19ea613 Default 0x0 63622 0 DriveFileProviderExtension: (RunningBoardServices) [com.apple.runningboard:connection] Creating connection to com.apple.runningboard 2025-07-18 11:32:05.803459-0700 0x19ea613 Default 0x0 63622 0 DriveFileProviderExtension: (libxpc.dylib) [com.apple.xpc:connection] [0x12f106e10] activating connection: mach=true listener=false peer=false name=com.apple.runningboard 2025-07-18 11:32:05.805893-0700 0x19ea613 Default 0x0 63622 0 DriveFileProviderExtension: (RunningBoardServices) [com.apple.runningboard:connection] Handshake succeeded 2025-07-18 11:32:05.805955-0700 0x19ea613 Default 0x0 63622 0 DriveFileProviderExtension: (RunningBoardServices) [com.apple.runningboard:connection] Identity resolved as xpcservice<clio.Drive.DriveFileProviderExtension([osservice<com.apple.FileProvider(501)>:990])(501)>{vt hash: 247410607}[uuid:454E32DB-3FB4-4DC6-9C05-F4B2F97333E0]{persona:9EF54117-4998-4D72-83C4-F12587C95FBA} but none of my print lines are being printed. I have code like this sprinkled through the methods: print("🔍 FileProviderExtension INIT - Logger configured") print("🔍 Domain: \(domain.displayName)") None of these show up anywhere. I also do a pure log stream with all system output, and there, too, I don't see anything. What am I missing? With my Obj-C version, all NSLogs used to show up as expected. With Swift, am I missing something?
2
0
100
Jul ’25
AsyncStream does not cancel inner Task
AsyncStream { continuation in Task { let response = await getResponse() continuation.yield(response) continuation.finish() } } In this WWDC video https://developer.apple.com/videos/play/wwdc2025/231/ at 8:20 the presenter mentions that if the "Task gets cancelled, the Task inside the function will automatically get cancelled too". The documentation does not mention anything like this. From my own testing on iOS 18.5, this is not true.
2
0
593
Jul ’25
App crashes on launch due to missing Swift Concurrency symbol
I'm encountering a crash on app launch. The crash is observed in iOS version 17.6 but not in iOS version 18.5. The only new notable thing I added to this app version was migrate to store kit 2. Below is the error message from Xcode: Referenced from: <DCC68597-D1F6-32AA-8635-FB975BD853FE> /private/var/containers/Bundle/Application/6FB3DDE4-6AD5-4778-AD8A-896F99E744E8/callbreak.app/callbreak Expected in: <A0C8B407-0ABF-3C28-A54C-FE8B1D3FA7AC> /usr/lib/swift/libswift_Concurrency.dylib Symbol not found: _$sScIsE4next9isolation7ElementQzSgScA_pSgYi_tYa7FailureQzYKFTu Referenced from: <DCC68597-D1F6-32AA-8635-FB975BD853FE> /private/var/containers/Bundle/Application/6FB3DDE4-6AD5-4778-AD8A-896F99E744E8/callbreak.app/callbreak Expected in: <A0C8B407-0ABF-3C28-A54C-FE8B1D3FA7AC> /usr/lib/swift/libswift_Concurrency.dylib dyld config: DYLD_LIBRARY_PATH=/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/usr/lib/libLogRedirect.dylib:/usr/lib/libBacktraceRecording.dylib:/usr/lib/libMainThreadChecker.dylib:/usr/lib/libRPAC.dylib:/System/Library/PrivateFrameworks/GPUToolsCapture.framework/GPUToolsCapture:/usr/lib/libViewDebuggerSupport.dylib``` and Stack Trace: ```* thread #1, stop reason = signal SIGABRT * frame #0: 0x00000001c73716f8 dyld`__abort_with_payload + 8 frame #1: 0x00000001c737ce34 dyld`abort_with_payload_wrapper_internal + 104 frame #2: 0x00000001c737ce68 dyld`abort_with_payload + 16 frame #3: 0x00000001c7309dd4 dyld`dyld4::halt(char const*, dyld4::StructuredError const*) + 304 frame #4: 0x00000001c73176a8 dyld`dyld4::prepare(...) + 4088 frame #5: 0x00000001c733bef4 dyld`start + 1748``` Note: My app is a Godot App and uses objc static libraries. I am using swift with bridging headers for interoperability. This issue wasn't observed until my last version in which the migration to storekit2 was the only notable change.
1
0
120
Jul ’25
Dynamically Create Tool Argument Type
According to the Tool documentation, the arguments to the tool are specified as a static struct type T, which is given to tool.call(argument: T) However, if the arguments are not known until runtime, is it possible to still create a Tool object with the proper parameters? Let's say a JSON-style dictionary is passed into the Tool init function to specify T, is this achievable?
1
0
408
Jul ’25