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

StoreKit2 Subscription Verification
My question is simple, I do not have much experience in writing swift code, I am only doing it to create a small executable that I can call from my python application which completes Subcription Management. I was hoping someone with more experience could point out my flaws along with giving me tips on how to verify that the check is working for my applicaiton. Any inight is appreciated, thank you. import Foundation import StoreKit class SubscriptionValidator { static func getReceiptURL() -> URL? { guard let appStoreReceiptURL = Bundle.main.appStoreReceiptURL else { print("No receipt found.") return nil } return appStoreReceiptURL } static func validateReceipt() -> Bool { guard let receiptURL = getReceiptURL(), let receiptData = try? Data(contentsOf: receiptURL) else { print("Could not read receipt.") return false } let receiptString = receiptData.base64EncodedString() let validationResult = sendReceiptToApple(receiptString: receiptString) return validationResult } static func sendReceiptToApple(receiptString: String) -> Bool { let isSandbox = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt" let urlString = isSandbox ? "https://sandbox.itunes.apple.com/verifyReceipt" : "https://buy.itunes.apple.com/verifyReceipt" let url = URL(string: urlString)! let requestData: [String: Any] = [ "receipt-data": receiptString, "password": "0b7f88907b77443997838c72be52f5fc" ] guard let requestBody = try? JSONSerialization.data(withJSONObject: requestData) else { print("Error creating request body.") return false } var request = URLRequest(url: url) request.httpMethod = "POST" request.httpBody = requestBody request.setValue("application/json", forHTTPHeaderField: "Content-Type") let semaphore = DispatchSemaphore(value: 0) var isValid = false let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil, let jsonResponse = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let status = jsonResponse["status"] as? Int else { print("Receipt validation failed.") semaphore.signal() return } if status == 0, let receipt = jsonResponse["receipt"] as? [String: Any], let inApp = receipt["in_app"] as? [[String: Any]] { for purchase in inApp { if let expiresDateMS = purchase["expires_date_ms"] as? String, let expiresDate = Double(expiresDateMS) { let expiryDate = Date(timeIntervalSince1970: expiresDate / 1000.0) if expiryDate > Date() { isValid = true } } } } semaphore.signal() } task.resume() semaphore.wait() return isValid } }
0
0
171
1w
SceneKit Performance Issues with Large Node Counts on iPad (10th Gen, iPadOS 18.3)
We’re developing an iPad application that visualizes 2D and 3D building floor plans, including a mesh network of nodes that control lighting and climate. The node count ranges from 1,000 to 15,000. We’re using SceneKit to dynamically render the floor plan and node mesh on an iPad 10th generation running iPadOS 18.3. While the core visualization works, we are experiencing significant performance degradation as the node count increases. Specifically: At 750–1,000 nodes, UI responsiveness noticeably declines. At 2,000 nodes, navigating the floor plan becomes nearly unusable. We attempted to optimize performance with a Geometric Pool algorithm, but the impact was minimal. Strangely, the same iPad handles 30,000+ 3D objects effortlessly when using Unity or Unreal Engine, raising the question of whether SceneKit may not be optimized for this scale. Our questions: Is SceneKit suitable for visualizing such large node counts, or are we hitting an inherent limitation of the framework? Are there best practices or optimization techniques for SceneKit that we might be missing? Should we consider a hybrid approach or fully transition to a different 3D engine for this use case? We’ve attached a code sample below demonstrating the issue. Any insights, suggestions, or experiences would be greatly appreciated! ContentView.swift
0
0
146
1w
CarPlay style API
Is there any way I can get updates when I change CarPlay style settings? I've tried CPSessionConfigurationDelegate.contentStyleChanged and CPTemplateApplicationSceneDelegate.contentStyleDidChange, but they always produce the same result. When I choose: Automatic -> I receive light in case of daylight; Always Dark and Always Show Dark Map toggle on -> dark Always Dark and Always Show Dark Map toggle off -> light. But it seems to be wrong, b/c CarPlay's toolbar is still dark, and I receive light. Is there a way to get a dark style when choosing Always Dark and Always Show Dark Map toggle off? Or at least get updates when the Always Show Dark Map toggle changes?
0
0
129
1w
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! 🙏🚀
1
1
288
1w
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
216
1w
swiftui fileimporter inside UIHostingController
I'm working on an old iOS app that started with objective-C + UIKit and has being migrated to Swift + SwiftUI. Currently its code is mostly Swift + SwiftUI but it has still some objective-C and some UIKit ViewControllers. One of the SwiftUI views uses fileImporter to open Files App and select a file from the device. This has been working well until iOS 18 is launched. With iOS 18 the file picker is not launching correctly and is frozen in every simulator (the unique real device I've could test with iOS 18 seemed to work correctly). I managed to clone my project and leave it with the minimal amount of files to reproduce this error. This is the code: AppDelegate.h #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> {} @property (strong, nonatomic) UIWindow *window; @end AppDelegate.m #import "AppDelegate.h" #import "MyApp-Swift.h" @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; FirstViewBuilder *viewBuilder = [[FirstViewBuilder alloc] init]; [viewBuilder show]; return YES; } @end FirstViewBuilder.swift import SwiftUI @objc class FirstViewBuilder: NSObject { private var view: UIHostingController<FirstView> @objc override init() { self.view = MyHostingController(rootView: FirstView()) } @objc func show() { let app = UIApplication.shared.delegate as? AppDelegate let window = app?.window window?.backgroundColor = .white // Use navigationController or view directly depending on use window?.rootViewController = view } } FirstView.swift import SwiftUI struct FirstView: View { @State var hasToOpenFilesApp = false var body: some View { VStack(alignment: .leading, spacing: 0) { Button("Open Files app") { hasToOpenFilesApp = true }.fileImporter(isPresented: $hasToOpenFilesApp, allowedContentTypes: [.text]) { result in switch result { case .success(let url): print(url.debugDescription) case .failure(let error): print(error.localizedDescription) } } } } } And finally, MyHostingController import SwiftUI class MyHostingController<Content>: UIHostingController<Content> where Content: View { override init(rootView: Content) { super.init(rootView: rootView) } @objc required dynamic init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.hidesBackButton = true } } Launching this in an iPhone 13 Pro (18.2) simulator I click on Open Files App, it takes 2 seconds to open it, and it opens full screen (not like a modal). Buttons on the top are behind the status bar and buttons at the bottom are behind the Home indicator. But it's worse because the user can't interact with this view, it's frozen. I created a fresh SwiftUI project just with this unique view and the fileimport worked as expected so I thought the problem was due to embed the SwiftUI view inside the UIHostingController. So I made these modifications to the minimal project: Remove the files AppDelegate, FirstViewBuilder and MyHostingController. Create this SwiftUI App file import SwiftUI @main struct MyApp: App { var body: some Scene { WindowGroup { FirstView() } } } And again the same problem with iOS 18. But if I launch this exact project in an iPhone 13 Pro (17.4) simulator and open the files apps (now it opens almost instantly) it works OK and shows the file picker as a modal, as expected, and I can interact with it and select files. Last thing I've tried is removing LaunchScreen.xib from my project and Launch screen interface file base name key from my info.plist but the problem keeps happening. I guess it must be due to my project configuration (too old) but I have no more ideas of where to look at. The possibility of having a fresh SwiftUI project and "move" the old project to the new one could take me several weeks and I discard it by the moment. Could I use another method to select files from SwiftUI views with iOS 18?
2
0
258
1w
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
0
251
1w
App terminated at launch exported on Xcode 16.2
when upgrading Xcode from 15.4 to 16.2, my apps crash at launch. device: iphone 14 pro max, iOS version 18.2.1 Termination Reason: DYLD 4 Symbol missing Symbol not found: _$s10Foundation4DateV4GRDB24DatabaseValueConvertibleA2dEP08databaseE0AD0dE0VvgTW Full Report Below: Full Report {"app_name":"myapp","timestamp":"2025-02-15 20:58:55.00 +0800","app_version":"5.25.0","slice_uuid":"dc349d86-392d-39fa-9cd3-daccab1db019","build_version":"0","platform":2,"bundleID":"com.xxxx.myapp","share_with_app_devs":1,"is_first_party":0,"bug_type":"309","os_version":"iPhone OS 18.2.1 (22C161)","roots_installed":0,"name":"myapp","incident_id":"99A2D5C2-3A04-47A7-9521-408E2287D0B4"} { "uptime" : 200000, "procRole" : "Foreground", "version" : 2, "userID" : 501, "deployVersion" : 210, "modelCode" : "iPhone15,3", "coalitionID" : 601, "osVersion" : { "isEmbedded" : true, "train" : "iPhone OS 18.2.1", "releaseType" : "User", "build" : "22C161" }, "captureTime" : "2025-02-15 20:58:55.5603 +0800", "codeSigningMonitor" : 2, "incident" : "99A2D5C2-3A04-47A7-9521-408E2287D0B4", "pid" : 8783, "translated" : false, "cpuType" : "ARM-64", "roots_installed" : 0, "bug_type" : "309", "procLaunch" : "2025-02-15 20:58:55.5448 +0800", "procStartAbsTime" : 5031986462126, "procExitAbsTime" : 5031986824477, "procName" : "myapp", "procPath" : "/private/var/containers/Bundle/Application/E0327E15-3AA9-42CA-8BEF-99076C11C04D/myapp.app/myapp", "bundleInfo" : {"CFBundleShortVersionString":"5.25.0","CFBundleVersion":"0","CFBundleIdentifier":"com.xxxx.myapp"}, "storeInfo" : {"deviceIdentifierForVendor":"D9AFB1A6-DDA6-462D-A27D-36E143C7ACF6","thirdParty":true}, "parentProc" : "launchd", "parentPid" : 1, "coalitionName" : "com.xxxx.myapp", "crashReporterKey" : "ded93d2da6d19b1e84aff2c00001f6ee1f7b0aca", "appleIntelligenceStatus" : {"state":"unavailable","reasons":["accessNotGranted","assetIsNotReady","siriAssetIsNotReady","notOptedIn","deviceNotCapable"]}, "wasUnlockedSinceBoot" : 1, "isLocked" : 0, "codeSigningID" : "com.xxxx.myapp", "codeSigningTeamID" : "8VGP475R33", "codeSigningFlags" : 570434305, "codeSigningValidationCategory" : 5, "codeSigningTrustLevel" : 4, "instructionByteStream" : {"beforePC":"5AAAACABAAAoAQAAMAEAADgBAABAAQAASAEAAGQBAAAwQYDSARAA1A==","atPC":"AwEAVH8jA9X9e7+p/QMAkcL0/pe/AwCR/XvBqP8PX9bAA1/WEC2A0g=="}, "bootSessionUUID" : "BF78EBB1-E385-4636-987E-B4388D80EBF3", "basebandVersion" : "3.20.05", "exception" : {"codes":"0x0000000000000000, 0x0000000000000000","rawCodes":[0,0],"type":"EXC_CRASH","signal":"SIGABRT"}, "termination" : {"code":4,"flags":518,"namespace":"DYLD","indicator":"Symbol missing","details":["(terminated at launch; ignore backtrace)"],"reasons":["Symbol not found: _$s10Foundation4DateV4GRDB24DatabaseValueConvertibleA2dEP08databaseE0AD0dE0VvgTW","Referenced from: /Volumes/VOLUME//myapp.app/myapp","Expected in: /Volumes/VOLUME//myapp.app/myapp"]}, "faultingThread" : 0, "threads" : [{"triggered":true,"id":2563160,"threadState":{"x":[{"value":6},{"value":4},{"value":6091179776},{"value":301},{"value":6091178752},{"value":0},{"value":6091174168},{"value":3776},{"value":32},{"value":6091178631},{"value":10},{"value":0},{"value":56},{"value":0},{"value":4439450793},{"value":6091174968},{"value":521},{"value":7593716520,"symbolLocation":420,"symbol":"__simple_bprintf"},{"value":0},{"value":0},{"value":6091178752},{"value":301},{"value":6091179776},{"value":4},{"value":6},{"value":9288},{"value":6091191552},{"value":8701512496,"symbolLocation":19168,"symbol":"dyld4::preallocator"},{"value":0}],"flavor":"ARM_THREAD_STATE64","lr":{"value":7594015840},"cpsr":{"value":2147487744},"fp":{"value":6091178704},"sp":{"value":6091178640},"esr":{"value":1442840704,"description":" Address size fault"},"pc":{"value":7593988164,"matchesCrashFrame":1},"far":{"value":0}},"frames":[{"imageOffset":442436,"symbol":"__abort_with_payload","symbolLocation":8,"imageIndex":1},{"imageOffset":470112,"symbol":"abort_with_payload_wrapper_internal","symbolLocation":104,"imageIndex":1},{"imageOffset":470164,"symbol":"abort_with_payload","symbolLocation":16,"imageIndex":1},{"imageOffset":22704,"symbol":"dyld4::halt(char const*, dyld4::StructuredError const*)","symbolLocation":300,"imageIndex":1},{"imageOffset":30132,"symbol":"dyld4::prepare(dyld4::APIs&, dyld3::MachOAnalyzer const*)","symbolLocation":4124,"imageIndex":1},{"imageOffset":198252,"symbol":"dyld4::start(dyld4::KernelArgs*, void*, void*)::$_0::operator()() const","symbolLocation":544,"imageIndex":1},{"imageOffset":195536,"symbol":"start","symbolLocation":2188,"imageIndex":1}]}], "usedImages" : [ { "source" : "P", "arch" : "arm64", "base" : 4375625728, "size" : 55197696, "uuid" : "dc349d86-392d-39fa-9cd3-daccab1db019", "path" : "/private/var/containers/Bundle/Application/E0327E15-3AA9-42CA-8BEF-99076C11C04D/myapp.app/myapp", "name" : "myapp" }, { "source" : "P", "arch" : "arm64e", "base" : 7593545728, "size" : 536896, "uuid" : "4eb7459f-e237-38ce-8240-3f3e2e1ce5ab", "path" : "/usr/lib/dyld", "name" : "dyld" }, { "size" : 0, "source" : "A", "base" : 0, "uuid" : "00000000-0000-0000-0000-000000000000" } ], "sharedCache" : { "base" : 6907789312, "size" : 4393861120, "uuid" : "16cc07dd-eea7-3049-9ee6-335fc7c37edf" }, "vmSummary" : "ReadOnly portion of Libraries: Total=259.2M resident=0K(0%) swapped_out_or_unallocated=259.2M(100%)\nWritable regions: Total=4240K written=144K(3%) resident=144K(3%) swapped_out=0K(0%) unallocated=4096K(97%)\n\n VIRTUAL REGION \nREGION TYPE SIZE COUNT (non-coalesced) \n=========== ======= ======= \nSTACK GUARD 16K 1 \nStack 1008K 1 \nVM_ALLOCATE 16K 1 \nVM_ALLOCATE (reserved) 672K 4 reserved VM address space (unallocated)\n__DATA 4868K 3 \n__DATA_CONST 1638K 2 \n__DATA_DIRTY 12K 1 \n__LINKEDIT 206.1M 2 \n__TEXT 53.2M 2 \n__TPRO_CONST 272K 1 \ndyld private memory 1024K 1 \nmapped file 61.3M 23 \npage table in kernel 144K 1 \n=========== ======= ======= \nTOTAL 330.0M 43 \nTOTAL, minus reserved VM space 329.3M 43 \n", "legacyInfo" : { "threadTriggered" : { } }, "logWritingSignature" : "c92c68c5c0a3817283c893ee8456b996f585f803", "trialInfo" : { "rollouts" : [ { "rolloutId" : "63f9578e238e7b23a1f3030a", "factorPackIds" : { "SMART_REPLY_ACTIONS_EN" : "64af1347f38420572631a103" }, "deploymentId" : 240000005 }, { "rolloutId" : "6761d0c9df60af01adb250fb", "factorPackIds" : { }, "deploymentId" : 240000001 } ], "experiments" : [ ] } }
1
0
222
1w
SwiftUI navigationDestination will make child view's stateObject init multi times with sheet modifier.
Below is my sample code. On the Home page, when I click "show sheet," the sheet page expands, and the StateObject inside the sheet is initialized once. However, when I click "show Fullscreen" and then click "show sheet" inside the fullscreen page, the sheet gets initialized twice. However, if I remove navigationDestination, this issue does not occur. This problem causes the network request in the sheet page to be triggered multiple times. Can someone tell me the reason? enum TestRouter: String, Hashable { case test var targetView: some View { Text("test") } var title: String { return "test title" } } @MainActor struct NavigationInnerView<Content>: View where Content: View { var contentView: () -> Content @MainActor public init(@ViewBuilder contentView: @escaping () -> Content) { self.contentView = contentView } var body: some View { NavigationStack() { contentView() .navigationDestination(for: TestRouter.self) { route in route.targetView } } .navigationViewStyle(StackNavigationViewStyle()) } } struct ContentView: View { @State var showFullScreen: Bool = false @State var showSheet: Bool = false var contentView: some View { VStack { VStack { Text("Home") Button { showFullScreen = true } label: { Text("show fullscreen") } Button { showSheet = true } label: { Text("show sheet ") } } } } var body: some View { NavigationInnerView { contentView .fullScreenCover(isPresented: $showFullScreen) { NavigationInnerView { FullScreenContentView() } } .sheet(isPresented: $showSheet) { NavigationInnerView { SheetContentView() } } } } } class FullScreenViewModel: ObservableObject { @Published var content: Bool = false init() { print("Full Screen ViewModel init") } } struct FullScreenContentView: View { @Environment(\.dismiss) var dismiss @State var showSheet: Bool = false @StateObject var viewModel: FullScreenViewModel = .init() init() { print("Full screen view init") } var body: some View { VStack { Text("FullScreen") Button { dismiss() }label: { Text("dismiss") } Button { showSheet = true } label: { Text("show sheet") } } .sheet(isPresented: $showSheet) { NavigationInnerView { SheetContentView() } } } } class SheetViewModel: ObservableObject { @Published var content: Bool = false init() { print("SheetViewModel init") } } struct SheetContentView: View { @Environment(\.dismiss) var dismiss @StateObject var viewModel = SheetViewModel() init() { print("sheet view init") } var body: some View { Text("Sheet") Button { dismiss() } label: { Text("dismiss") } } } #Preview { ContentView() }
3
0
212
1w
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
210
1w
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
243
2w
Implementing RawRepresentable for a DictionaryType has broken my Test target build. Not sure how to fix things...
For my app I've created a Dictionary that I want to persist using AppStorage In order to be able to do this, I added RawRepresentable conformance for my specific type of Dictionary. (see code below) typealias ScriptPickers = [Language: Bool] extension ScriptPickers: @retroactive RawRepresentable where Key == Language, Value == Bool { public init?(rawValue: String) { guard let data = rawValue.data(using: .utf8), let result = try? JSONDecoder().decode(ScriptPickers.self, from: data) else { return nil } self = result } public var rawValue: String { guard let data = try? JSONEncoder().encode(self), // data is Data type let result = String(data: data, encoding: .utf8) // coerce NSData to String else { return "{}" // empty Dictionary represented as String } return result } } public enum Language: String, Codable, { case en = "en" case fr = "fr" case ja = "ja" case ko = "ko" case hr = "hr" case de = "de" } This all works fine in my app, however trying to run any tests, the build fails with the following: Conflicting conformance of 'Dictionary<Key, Value>' to protocol 'RawRepresentable'; there cannot be more than one conformance, even with different conditional bounds But then when I comment out my RawRepresentable implementation, I get the following error when attempting to run tests: Value of type 'ScriptPickers' (aka 'Dictionary<Language, Bool>') has no member 'rawValue' I hope Joseph Heller is out there somewhere chuckling at my predicament any/all ideas greatly appreciated
1
0
277
1w
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 &gt; 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) -&gt; (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 &gt; 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) -&gt; 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) &gt; maxSizeInBytes, compression &gt; 0 { compression -= step imageData = jpegData(compressionQuality: compression) } return imageData } }
1
0
238
2w
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
399
2w
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
194
2w
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
381
2w
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
284
2w