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

Posts under Swift tag

200 Posts

Post

Replies

Boosts

Views

Activity

Xcode: Skipping Duplicate Build File in Compile Sources in a .swiftpm Project – How to Fix?
I'm trying to add Assets.xcassets to a .swiftpm project, but I'm getting the warning: ⚠️ Ignoring duplicate build file in build source build phase (Just to know, that is about developing in XCODE, in Swift Playgrounds does not appear it, even in this second being harder to setting up) The problem is that there are no “Build Phases” in XCODE to remove duplicate files manually. I've already tried adding the path of Assets.xcassets in the resources property of Package.swift, like: .executableTarget( name: "AppModule", path: ".", resources: [ .process("Assets.xcassets") ] ) Even so, the warning persists. Does anyone know how to solve this? Is there any way to remove duplicate references or force a cleanup of the Swift Package Manager cache to fix it? I appreciate any tips! 🙏🚀
2
2
538
Feb ’25
Set UILabel color in alertController
I have an alertController that is presented as popover on iPad let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: alertStyle) if let ppc = alertController.popoverPresentationController { // … } Is it possible to change the message font color (which is really very light on iPad) ? It is OK on iPhone with the same alert (not popover): text is much more readable:
1
0
333
Feb ’25
3D scanning and 3D model with texture mapping
I am new here and would appreciate help in coding or an explanation what to use in swift for an app which will be able to capture LiDAR scanning and RGB data from taken pictures, generate a 3D mesh, and create .OBJ, .MTL, and .JPEG file set for further manipulation of 3D model. I am able to create from LiDAR scanning 3D mesh and .OBJ file but can not generate .MTL and .JPEG for a texture of 3D model.
1
0
364
Feb ’25
EXC_BREAKPOINT in BGAppRefreshTask
When I run my app with XCode on my iPhone, and then moved into the background, I'm getting a EXC_BREAKPOINT exception after a few minutes, seemingly when iOS attempts to call my app with a BGAppRefreshTask: Thread 23 Queue: com.apple.BGTaskScheduler (com.mycompany.MyApp.RefreshTask) (serial) 0 _dispatch_assert_queue_fail 12 _pthread_wqthread Enqueued from com.apple.duet.activityscheduler.client.xpcqueue (Thread 23) 0 dispatch_async 20 start_wqthread I can't quite understand the reason from this crash. In the background task, I'm attempting to update live activities. In the process, it might encounter code that calls MainActor and manipulate @Observable objects. Might that be the reason?
2
1
444
Feb ’25
[iOS, SwiftUI] Navigation Bar background is always hidden when navigation destination is TabView
Hello! I have a destination navigation which is TabVIew where each tab item is ScrollView. And when scrolling content of any of tab items is underneath navigation bar its background is always hidden. But at the same time tab bar background is toggled depending on scrolling content position. I expected it would work with TabView the same as with any other view. Is it supposed to work like that?
2
0
289
Feb ’25
URL passed as attachment to notification is deleted when notification is added
I create a notification with an image attachment: let center = UNUserNotificationCenter.current() center.delegate = self let content = UNMutableNotificationContent() // some more stuff… let paths = NSSearchPathForDirectoriesInDomains( FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true) let documentsDirectory = paths[0] as NSString let fileExtPNG = "#" + "\(imageName)" + " photo.png" let fileNamePNG = documentsDirectory.appendingPathComponent(fileExtPNG) as String url = URL(fileURLWithPath: fileNamePNG) let attachment = try UNNotificationAttachment(identifier: "Image", url: url, options: nil) content.attachments = [attachment] I then add the request: let request = UNNotificationRequest(identifier:requestIdentifier, content: content, trigger: nil) center.removePendingNotificationRequests(withIdentifiers: [requestIdentifier]) center.add(request) {(error) in } Problem: when I later test (once notification has been registered), the file do not exist anymore at the url. I've commented out the add request to confirm. I have a work around, by creating a temporary copy of the file at the URL and pass it in the attachment. Then, everything works fine and the copy is deleted. But that's a bit bizarre. What am I missing here ?
2
0
355
Feb ’25
Issues with using ClassifyImageRequest() on an Xcode simulator
Hello, I am developing an app for the Swift Student challenge; however, I keep encountering an error when using ClassifyImageRequest from the Vision framework in Xcode: VTEST: error: perform(_:): inside 'for await result in resultStream' error: internalError("Error Domain=NSOSStatusErrorDomain Code=-1 \"Failed to create espresso context.\" UserInfo={NSLocalizedDescription=Failed to create espresso context.}") It works perfectly when testing it on a physical device, and I saw on another thread that ClassifyImageRequest doesn't work on simulators. Will this cause problems with my submission to the challenge? Thanks
5
1
745
Feb ’25
Nested method calls in `context.perform` with Swift 6
I'm calling a method with the context as parameter, within the context's perform block – is this really not legal in Swift 6? actor MyActor { func bar(context: NSManagedObjectContext) { /* some code */ } func foo(context: NSManagedObjectContext) { context.performAndWait { self.bar(context: context) // WARN: Sending 'context' risks causing data races; this is an error in the Swift 6 language mode // 'self'-isolated 'context' is captured by a actor-isolated closure. actor-isolated uses in closure may race against later nonisolated uses // Access can happen concurrently } } } The warning appears when I call a method with a context parameter, within the performAndWait-block. Background: In my app I have methods that takes in API data, and I need to call the same methods from multiple places with the same context to store it, and I do not want to copy paste the code and have hundreds of lines of duplicate code. Is there a well-known "this is how you should do it" for situations like this? This is related to a previous post I made, but it's a bit flimsy and got no response: https://developer.apple.com/forums/thread/770605
1
1
853
Feb ’25
Won't compile/build after a "Clean Build Folder..." invoked
I have 2 versions of my app. This version I issued the "Clean Build Folder..." command. After doing so it will no longer compile/build. I've restored the directory to a copy prior to the Clean Build Folder with same result. The other version of this code will build and execute. Command SwiftCompile failed with a nonzero exit code /Users/martinwoscek/develop/iOS_switft_DEVELOP/FullScreenCamera-master-no_drivemonitor/AV Foundation/Base.lproj/LaunchScreen.storyboard: Encountered an error communicating with IBAgent-iOS. Showing Recent Issues . . . Command SwiftCompile failed with a nonzero exit code Command SwiftCompile failed with a nonzero exit code Build failed 2/11/25, 8:15 AM 1.4 seconds
4
0
359
Feb ’25
SwiftUI Main Actor Isolation Error with PhotosPicker
I'm getting the following error in my SwiftUI code: "Main actor-isolated property 'avatarImage' can not be referenced from a Sendable closure" I don't understand how to fix it. This happens in the following code: You can copy-paste this into an empty project and make sure to have Swift 6 enabled under the Build Settings > Swift Language Version import PhotosUI import SwiftUI public struct ContentView: View { @State private var avatarItem: PhotosPickerItem? @State private var avatarImage: Image? @State private var avatarData: Data? public var body: some View { VStack(spacing: 30) { VStack(alignment: .center) { PhotosPicker(selection: $avatarItem, matching: .images) { if let avatarImage { avatarImage .resizable() .aspectRatio(contentMode: .fill) .frame(width: 100, height: 100) .foregroundColor(.gray) .background(.white) .clipShape(Circle()) .opacity(0.75) .overlay { Image(systemName: "pencil") .font(.title) .shadow(radius: 5) } } else { Image(systemName: "person.circle.fill") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 100, height: 100) .foregroundColor(.gray) .background(.white) .clipShape(Circle()) .opacity(0.75) .overlay { Image(systemName: "pencil") .font(.title) .shadow(radius: 5) } } } } } .onChange(of: avatarItem) { Task { if let data = try? await avatarItem?.loadTransferable( type: Data.self ) { if let processed = processImage(data: data) { avatarImage = processed.image avatarData = processed.data } else { } } } } } private func processImage(data: Data) -> (image: Image?, data: Data?)? { guard let uiImage = UIImage(data: data)?.preparingForDisplay() else { return nil } // Check original size let sizeInMB = Double(data.count) / (1024 * 1024) // If image is larger than 1MB, compress it if sizeInMB > 1.0 { guard let compressedData = uiImage.compress() else { return nil } return (Image(uiImage: uiImage), compressedData) } return (Image(uiImage: uiImage), data) } } #Preview { ContentView() } public extension UIImage { func compress(to maxSizeInMB: Double = 1.0) -> Data? { let maxSizeInBytes = Int( maxSizeInMB * 1024 * 1024 ) // Convert MB to bytes var compression: CGFloat = 1.0 let step: CGFloat = 0.1 var imageData = jpegData(compressionQuality: compression) while (imageData?.count ?? 0) > maxSizeInBytes, compression > 0 { compression -= step imageData = jpegData(compressionQuality: compression) } return imageData } }
1
0
519
Feb ’25
Wifi connection made with NEHotspotConfigurationManager gets disconnected
I'm using the NEHotspotConfigurationManager class, with joinOnce = false, to connect to a Wi-Fi network that lacks internet access (IoT device). After restarting my iPhone, the first connection to this network disconnects automatically in less than a minute. All subsequent connections remain stable without disconnecting. What could be causing this?
4
0
311
Feb ’25
How do I locate and this Bundle Error
❌ Could not find email_ai.py in the app bundle. Available files: [] The error above is what I’m encountering. I’ve placed the referenced file both in the project directory and inside the app. However, every time I remove and reinsert the file into the folder within the app, it prompts me to designate the targets—I select all, but this doesn’t resolve the issue. I’m unsure how to properly reference the file so that it is recognised and included in the bundle. Any guidance would be greatly appreciated. this is my build phase: #!/bin/sh set -x # Prints each command before running it (for debugging) pwd # Shows the current working directory echo "$SRCROOT" # Shows what Xcode thinks is the project root ls -l "$SRCROOT/EmailAssistant/EmailAssistant/PythonScripts" # Lists files in the script folder export PYTHONPATH="/Users/caesar/.pyenv/versions/3.11.6/bin" /Users/caesar/.pyenv/versions/3.11.6/bin/python3 "$SRCROOT/EmailAssistant/EmailAssistant/PythonScripts/email_ai.py" echo "Script completed."
1
0
455
Feb ’25
Picked photo in the gallery does not recognise image orientation
When picking a photo in the gallery, whatever the orientation of the original image, size is always as landscape if let image = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.editedImage)] as? UIImage { print("picked original", image.size) For a portrait photo: picked original (1122.0, 932.0) For a landscape: picked original (1124.0, 844.0) What am I missing ?
1
0
346
Feb ’25
Swift Student Challenge table's two questions
I am currently filling out the Swift Student Challenge form, and I have two questions that I hope to get clarified: One of the options asks, “Did you use open source software, other than Swift?” I would like to know what is meant by “open source software” in this context. Does it refer to IDEs (like Xcode) or programming languages and frameworks (such as Python, ARKit)? Are Apple frameworks (e.g., SwiftUI, ARKit, etc.) and certain third-party tools (such as Xcode, Blender, etc.) considered “open source software”? I would like to provide a demo video to ensure that the reviewers can use the app properly and experience all of its features in the shortest amount of time. For certain reasons, I do not plan to play the video directly in the App Playground. Instead, I intend to include a link in the “Comments” section at the end of the form, which will redirect to a webpage (requiring an internet connection) containing the demo video. Will the reviewers be able to view the link and access the video as intended? I would greatly appreciate any responses to these questions!
1
0
561
Feb ’25
Swift Student Challenge Devices / Simulator preferred building device
For the SSDC submission, the app playground must run on Swift Playgrounds 4.5+ or Xcode 16+. Key questions: In Swift Playgrounds, is the app tested on iPadOS or macOS? In Xcode 16+, is the playground tested using Mac Catalyst, an iPad simulator, or an iPhone simulator? The submission form only mentions a simulator but doesn’t specify which one. Can I build an app primarily for iPhone (portrait mode), or is it better to focus on iPad (landscape mode) if that’s the expected testing environment in all cases?
0
1
426
Feb ’25
not work paragraphStyle in AttributedString
I tried to create a Text View using attributedString. I want to set the line height using paragraphStyle and return the Text, but paragraphStyle is not being applied. Why is that? extension Text { init?(_ content: String, font: StyleType, color: Color = .ppBlack) { var attributedString = AttributedString(content) attributedString.font = Font.custom(font.fontWeight, fixedSize: font.fontSize) attributedString.foregroundColor = color let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.minimumLineHeight = 16 paragraphStyle.maximumLineHeight = 16 paragraphStyle.lineSpacing = 0 attributedString.mergeAttributes(.init([.paragraphStyle: paragraphStyle])) self = Text(attributedString) } }
1
0
319
Feb ’25