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

iPhone 16 Pro Camera Preview freeze
Hi all, we are working on iOS application that includes the camera functionality. This week we have received a few customer complaints regarding the camera usage with iPhone 16/16 Pro, both of the customers said that they have an issue with the camera preview(when the camera is open) the camera preview is just freezer but any other functionally and UI works as expected. Moreover the issue happens only for back camera, the front camera works perfectly. We have tested it in context of iOS 18 with iPhone 14/15/15 Pro/15 Pro Max but all devices with iOS 18 works perfectly without any issues. So we assumed there was no issues with iOS 18 but some breaking changes with the new iPhone 16/16 pro cameras were introduced that caused this effect. Unfortunatly, currently we can't test directly usign the iPhone 16/16 Pro since we have't these devices. We are using SwiftUI framework and here the implementation of the camera preview: VideoPreviewLayer final class CameraPreviewView: UIView { var previewLayer: AVCaptureVideoPreviewLayer { guard let layer = layer as? AVCaptureVideoPreviewLayer else { fatalError("Layer expected is of type VideoPreviewLayer") } return layer } var session: AVCaptureSession? { get { return previewLayer.session } set { previewLayer.session = newValue } } override class var layerClass: AnyClass { AVCaptureVideoPreviewLayer.self } } UIKit -> SwiftUI struct CameraRecordingView: UIViewRepresentable { @ObservedObject var cameraManager: CameraManager func makeUIView(context: Context) -> CameraPreviewView { let previewView = CameraPreviewView() previewView.session = cameraManager.session /// AVCaptureSession previewView.previewLayer.videoGravity = .resizeAspectFill return previewView } func updateUIView(_ uiView: CameraPreviewView, context: Context) { } } Setup camera input private func saveInput(input: AVCaptureDevice) { /// Where input is AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) do { let cameraInput = try AVCaptureDeviceInput(device: input) if session.canAddInput(cameraInput) { session.addInput(cameraInput) /// session is AVCaptureSession } else { sendError(error: .cannotAddInput) status = .failed } } catch { if error.nsError.code == -11852 { sendError(error: .microphoneError) } else { sendError(error: .createCaptureInput(error)) } status = .failed } } Does anybody have similar issues with iPhone 16/16 Pro? We would appreciate any ideas of how to potentially resolve the issue.
1
0
420
Sep ’24
How to I archive macros into a static library as xcframework?
I'm trying to make an xcframework from my static library (SPM btw) with macros. My script doesn't work properly My SPM declaration of macros: // swift-tools-version: 5.9 // The swift-tools-version declares the minimum version of Swift required to build this package. import CompilerPluginSupport import PackageDescription let package = Package( name: "SomeMacr", platforms: [.macOS(.v10_15), .iOS(.v13), .tvOS(.v13), .macCatalyst(.v13)], products: [ .library( name: "SomeMacr", targets: ["SomeMacr"] ), .executable( name: "SomeMacrClient", targets: ["SomeMacrClient"] ) ], dependencies: [ .package(url: "https://github.com/apple/swift-syntax.git", from: "509.0.0") ], targets: [ .macro( name: "SomeMacrMacros", dependencies: [ .product(name: "SwiftSyntaxMacros", package: "swift-syntax"), .product(name: "SwiftCompilerPlugin", package: "swift-syntax") ] ), .target(name: "SomeMacr", dependencies: ["SomeMacrMacros"]), .executableTarget(name: "SomeMacrClient", dependencies: ["SomeMacr"]), .testTarget( name: "SomeMacrTests", dependencies: [ "SomeMacrMacros", .product(name: "SwiftSyntaxMacrosTestSupport", package: "swift-syntax") ] ) ] ) My .sh script: xcodebuild archive \ -scheme $1 \ -sdk iphoneos \ -archivePath "Products/archives/ios_devices.xcarchive" \ SKIP_INSTALL=NO \ BUILD_LIBRARY_FOR_DISTRIBUTION=YES xcodebuild archive \ -scheme $1 \ -sdk iphonesimulator \ -archivePath "Products/archives/ios_simulators.xcarchive" \ SKIP_INSTALL=NO \ BUILD_LIBRARY_FOR_DISTRIBUTION=YES xcodebuild archive \ -scheme $1 \ -sdk macosx \ -archivePath "Products/archives/macos.xcarchive" \ SKIP_INSTALL=NO \ BUILD_LIBRARY_FOR_DISTRIBUTION=YES xcodebuild -create-xcframework \ -library Products/archives/ios_devices.xcarchive/Products/Library/Frameworks/lib$1.a \ -library Products/archives/ios_simulators.xcarchive/Products/Library/Frameworks/lib$1.a \ -library Products/archives/macos.xcarchive/Products/Library/Frameworks/lib$1.a \ -output Products/xc/$1.xcframework It requires destination (But in other tutorials, authors clearly shows, that after this script I will get an xcframework) xcodebuild: error: Building a Swift package requires that a destination is provided using the "-destination" option. The "-showdestinations" option can be used to list the available destinations But when I setup the destination it was compiled to exec file, which I don't mind how to include to another SPM package / or xcframework What am I doing wrong?
4
0
284
Oct ’24
UndoManager with SwiftData Not Registering Single Undo Actions Properly in macOS Sonoma 14.x
I am encountering an issue with the UndoManager functionality in a SwiftUI application that integrates SwiftData for persistence. This issue occurs specifically in macOS 14 (Sonoma) but works as expected on macOS 15 (Sequoia). The focused test app I have prepared for demonstration allows users to create ParentItem objects, and for each ParentItem, users can add multiple ChildItem objects. The undo functionality (via Cmd+Z) is not working as expected in Sonoma. When I try to undo a ChildItem addition, the UndoManager does not revert just the last ChildItem added, but instead removes all ChildItems that were added in that session. Expected Behavior On macOS 14 (Sonoma), I expect the UndoManager to undo only the most recent transaction (in this case, a single ChildItem insert), similar to how it functions on macOS 15 (Sequoia). Each ChildItem insertion should be treated as a separate undoable action. Current Behavior In macOS Sonoma, pressing Cmd+Z undoes the entire list of ChildItems added to a ParentItem in the current session, rather than just the most recent ChildItem. This appears to be an issue with undo grouping, but I’ve confirmed that no explicit grouping is being used. Question Is this an issue with UndoManager in macOS Sonoma, particularly in how it interacts with SwiftData persistence? What changes should I make to ensure that each ChildItem insert is treated as an individual undo action in macOS Sonoma, just as it works in Sequoia? Any guidance on isolating the issue or recommended workarounds would be appreciated. I would expect that undo actions for each child addition would be treated as separate transactions, not grouped. Steps Taken to Solve the Problem I attempted to manually save the model context (modelContext.save()) after each ChildItem insert to ensure proper persistence. I also verified that UndoManager was not grouping operations explicitly by calling beginUndoGrouping() or endUndoGrouping() myself. This issue seems to be tied specifically to macOS Sonoma, as it does not occur on macOS Sequoia, where undoing behaves as expected. Conditions macOS 14 Sonoma: The issue occurs consistently. macOS 15 Sequoia: The issue does not occur. This issue appears to be independent of hardware, as I’ve tested it on multiple machines. APIs/Features Potentially Involved UndoManager in a SwiftUI application SwiftData for persistence (using modelContext.save()) macOS version-specific behavior Steps to reproduce Clone test project (https://github.com/Maschina/SwiftDataUndoManagerExample), compile and run Create a new ParentItem in the app (via plus toolbar button in the sidebar). Add multiple ChildItems to the ParentItem (via plus toolbar button in the content / middle column of the navigation split view). Press Cmd+Z to undo the last addition.
2
0
337
1w
iOS: I need to convert CMSampleBuffer Linear PCM audio to MPEG-4 AAC
Hello, I am a deaf-blind wheelchair user, and I program in Swift using a braille display. I’m reaching out for your help on an issue I’ve been struggling to solve. Basically, when I extract a CMSampleBuffer from an AVAsset of a video, it comes with the Audio Format ID as Linear PCM. However, when I try to pass this CMSampleBuffer to write another video using AVAssetWriter, the video ends up muted. The audio settings of the output video are configured to MPEG-4 AAC, but the input CMSampleBuffer has the Audio Format ID as Linear PCM. I would like to request an extension for CMSampleBuffer that converts Linear PCM audio to MPEG-4 AAC. I’ve searched extensively and couldn’t find anything. Looking forward to your help. Thank you.
1
0
236
Oct ’24
dismissWindow alternative for macOS 13?
Currently for my SwiftUI application i'm using dismissWindow() to close my windows. However, I want to make my app compatible on macOS 13 to enable a wider audience. My current usage of this function is as follows: func reloadContentViewAfterDelete() { @Environment(\.openWindow) var openWindow @Environment(\.dismissWindow) var dismissWindow dismissWindow(id: "content") openWindow(id: "content") }
1
0
191
Sep ’24
Trouble with getting a background refresh task working
I am able to setup and schedule a background refresh task as well as manually trigger it via Xcode and the simulator tied to my iPhone 11 Pro test phone using the e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier: However, it won't execute on the app on it's own. And yes, the pinfo.list entries are correct and match! I know the scheduler is not exact on timing but it's just not executing on its own. Since I can trigger manually it I'm pretty sure the code is good but I must be missing something. I created an observable object for this code and the relevant parts look like this: class BackgroundTaskHandler: ObservableObject { static let shared = BackgroundTaskHandler() var taskState: BackgroundTaskState = .idle let backgroundAppRefreshTask = "com.opexnetworks.templateapp.shell.V1.appRefreshTask" func registerBackgroundTask() { BGTaskScheduler.shared.register(forTaskWithIdentifier: backgroundAppRefreshTask, using: nil) { task in self.handleAppRefresh(task: task as! BGAppRefreshTask) } self.updateTaskState(to: .idle, logMessage: "✅ Background app refresh task '\(backgroundAppRefreshTask)' registered.") BGTaskScheduler.shared.register(forTaskWithIdentifier: backgroundTaskIdentifier, using: nil) { task in self.handleProcessingTask(task: task as! BGProcessingTask) } self.updateTaskState(to: .idle, logMessage: "✅ Background task identifier '\(backgroundTaskIdentifier)' registered.") } // Handle the app refresh task private func handleAppRefresh(task: BGAppRefreshTask) { self.updateTaskState(to: .running, logMessage: "🔥 app refresh task is now running.") PostNotification.sendNotification(title: "Task Running", body: "App refresh task is now running.") let queue = OperationQueue() queue.maxConcurrentOperationCount = 1 let operation = BlockOperation { self.doSomeShortTaskWork() } task.expirationHandler = { self.updateTaskState(to: .expired, logMessage: "💀 App refresh task expired before completion.") PostNotification.sendNotification(title: "Task Expired", body: "App refresh task expired before completion \(self.formattedDate(Date())).") operation.cancel() } operation.completionBlock = { if !operation.isCancelled { self.taskState = .completed } task.setTaskCompleted(success: !operation.isCancelled) let completionDate = Date() UserDefaults.standard.set(completionDate, forKey: "LastBackgroundTaskCompletionDate") self.updateTaskState(to: .completed, logMessage: "🏁 App refresh task completed at \(self.formattedDate(completionDate)).") PostNotification.sendNotification(title: "Task Completed", body: "App refresh task completed at: \(completionDate)") self.scheduleAppRefresh() // Schedule the next one } queue.addOperation(operation) } func scheduleAppRefresh() { // Check for any pending task requests BGTaskScheduler.shared.getPendingTaskRequests { taskRequests in let refreshTaskIdentifier = self.backgroundAppRefreshTask let refreshTaskAlreadyScheduled = taskRequests.contains { $0.identifier == refreshTaskIdentifier } if refreshTaskAlreadyScheduled { self.updateTaskState(to: .pending, logMessage: "⚠️ App refresh task '\(refreshTaskIdentifier)' is already pending.") // Iterate over pending requests to get details for taskRequest in taskRequests where taskRequest.identifier == refreshTaskIdentifier { let earliestBeginDate: String if let date = taskRequest.earliestBeginDate { earliestBeginDate = self.formattedDate(date) } else { earliestBeginDate = "never" } self.updateTaskState(to: .pending, logMessage: "⚠️ Pending Task: \(taskRequest.identifier), Earliest Begin Date: \(earliestBeginDate)") } // Optionally, show a warning message to the user in your app PostNotification.sendNotification(title: "Pending Tasks", body: "App refresh task is already pending. Task scheduling cancelled.") return } else { // No pending app refresh task, so schedule a new one let request = BGAppRefreshTaskRequest(identifier: refreshTaskIdentifier) request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60) // Earliest in 15 minutes do { try BGTaskScheduler.shared.submit(request) self.taskState = .scheduled self.updateTaskState(to: .scheduled, logMessage: "✅ App refresh task '\(refreshTaskIdentifier)' successfully scheduled for about 15 minutes later.") PostNotification.sendNotification(title: "Task Scheduled", body: "App refresh task has been scheduled to run in about 15 minutes.") } catch { print("Could not schedule app refresh: \(error)") self.taskState = .failed self.updateTaskState(to: .failed, logMessage: "❌ Failed to schedule app refresh task.") } } } } // Short task work simulation private func doSomeShortTaskWork() { print("Doing some short task work...") // Simulate a short background task (e.g., fetching new data from server) sleep(5) print("Short task work completed.") } In my AppDelegate I trigger the registerBackground task in the didFinishLaunchingWithOptions here: BackgroundTaskHandler.shared.registerBackgroundTask() And I scheduled it here in the launch view under a task when visible: .task { BackgroundTaskHandler.shared.scheduleAppRefresh() } I've also tried the last in the AppDelegate after registering. either way the task schedules but never executes.
4
0
333
Sep ’24
Stored property 'base' of 'Sendable'-conforming struct 'AnyShape' has non-sendable type '(CGRect) -> Path'; this is an error in the Swift 6 language mode
Since I updated my project I'm getting this error Stored property 'base' of 'Sendable'-conforming struct 'AnyShape' has non-sendable type '(CGRect) -> Path'; this is an error in the Swift 6 language mode I get this error at that struct, more specifically on the base variable public struct AnyShape: Shape { private var base: (CGRect) -> Path public init<S: Shape>(shape: S) { base = shape.path(in:) } public func path(in rect: CGRect) -> Path { base(rect) } } I have no idea how to solve this issue, I've been looking on the internet for same issues and get nothing yet
1
0
456
Sep ’24
IIOScanner and PHImageIODecoder crash
I have a user who keeps crashing on his iOS 18 device, I need some help~ Exception 1, Code 26, Subcode 8 > Attempted to dereference garbage pointer 0x1a. 0 ImageIO IIOScanner::getVal32() + 36 1 ImageIO PSDReadPlugin::initialize(IIODictionary*) + 620 2 ImageIO PSDReadPlugin::initialize(IIODictionary*) + 620 3 ImageIO IIOReadPlugin::callInitialize() + 400 4 ImageIO IIO_Reader::initImageAtOffset(CGImagePlugin*, unsigned long, unsigned long, unsigned long) + 164 5 ImageIO IIOImageSource::makeImagePlus(unsigned long, IIODictionary*) + 832 6 ImageIO IIOImageSource::getPropertiesAtIndexInternal(unsigned long, IIODictionary*) + 72 7 ImageIO IIOImageSource::createThumbnailAtIndex(unsigned long, IIODictionary*, int*) + 1352 8 ImageIO CGImageSourceCreateThumbnailAtIndex + 740 9 Photos _createDecodedImageUsingImageIOWithFileUrlOrData + 856 10 Photos __91-[PHImageIODecoder decodeImageFromData:orFileURL:options:existingRequestHandle:completion:]_block_invoke_2 + 176 11 libdispatch.dylib _dispatch_call_block_and_release + 32 12 libdispatch.dylib _dispatch_client_callout + 20 13 libdispatch.dylib _dispatch_continuation_pop + 596 14 libdispatch.dylib _dispatch_async_redirect_invoke + 580 15 libdispatch.dylib _dispatch_root_queue_drain + 392 16 libdispatch.dylib _dispatch_worker_thread2 + 156 17 libsystem_pthread.dylib _pthread_wqthread + 228
1
0
209
Sep ’24
Sending main actor-isolated value of type 'PurchaseAction' with later accesses to nonisolated context risks causing data races
Trying to migrate to Swift 6. However getting this error when using SwiftUI StoreKit purchase environment. Sending main actor-isolated value of type 'PurchaseAction' with later accesses to nonisolated context risks causing data races @Environment(\.purchase) private var purchase let result = try await purchase(product)
1
0
390
Sep ’24
UIKit in SwiftUI memory leak while displaying images
I'm using UIKit to display a long list of large images inside a SwiftUI ScrollView and LazyHStack using UIViewControllerRepresentable. When an image is loaded, I'm using SDWebImage to load the image from the disk. As the user navigates through the list and continues to load more images, more memory is used and is never cleared, even as the images are unloaded by the LazyHStack. Eventually, the app reaches the memory limit and crashes. This issue persists if I load the image with UIImage(contentsOfFile: ...) instead of SDWebImage. How can I free the memory used by UIImage when the view is removed? ScrollView(.horizontal, showsIndicators: false) { LazyHStack(spacing: 16) { ForEach(allItems) { item in TestImageDisplayRepresentable(item: item) .frame(width: geometry.size.width, height: geometry.size.height) .id(item.id) } } .scrollTargetLayout() } import UIKit import SwiftUI import SDWebImage class TestImageDisplay: UIViewController { var item: TestItem init(item: TestItem) { self.item = item super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) imageView.center = view.center view.addSubview(imageView) imageView.sd_setImage(with: item.imageURL, placeholder: nil) } } struct TestImageDisplayRepresentable: UIViewControllerRepresentable { var item: TestItem func makeUIViewController(context: Context) -> TestImageDisplay { return TestImageDisplay(item: item) } func updateUIViewController(_ uiViewController: TestImageDisplay, context: Context) { uiViewController.item = item } }
0
0
296
Sep ’24
What's the correct way to check for unavailable API?
I ran into a problem recently with my production app and an update for iOS 18. In this example I was using a new API added to the RC candidate of iOS 18.0, using this API as an example, I couldn't find a satisfactory way to avoid crashing on iOS 18.1 where the API was not available. I had plenty of users running the iOS 18.1 Beta and ultimately it's my fault if a version of my app did work, and then didn't after an update.... This code causes a crash on iOS 18.1 beta as the .appleSleepingBreathingDisturbances API doesn't seem to have made it's way into the beta: if #available(iOS 18.0, *), #available(watchOS 11, *) { healthKitTypesToRead.insert(HKQuantityType.quantityType(forIdentifier: .appleSleepingBreathingDisturbances)!) } I tried this but it still crashed on 18.1: if #available(iOS 18.0, *), #available(watchOS 11, *) { if let newQuantity = HKQuantityType.quantityType(forIdentifier: .appleSleepingBreathingDisturbances) { healthKitTypesToRead.insert(newQuantity) } } In the end the only way I could resolve this was the following: if #available(iOS 18.1, *){ // Do nothing } else if #available(iOS 18.0, *), #available(watchOS 11, *) { if let newQuantity = HKQuantityType.quantityType(forIdentifier: .appleSleepingBreathingDisturbances) { healthKitTypesToRead.insert(newQuantity) } } This seems like a poor solution and I'll have to ensure I release a new version of the app once iOS 18.1 has the available API added to enable support for the feature. How could I have checked availability for this API correctly without causing the app to crash? I'm asking this question more as a Swift language feature rather than issue with the specific API as I'm sure that will get resolved soon anyway. Thanks
4
1
548
Sep ’24
what's wrong with `ToolbarItemGroup(placement: .keyboard)` inside `TavView`?
Why is there inconstancy of appearing the keyboard tool bar Item with tab view? Try to go to second tab and focus the field. Sometimes it does not appear (in my more complex project it does not appear >90% times). import SwiftUI struct MainTabView: View { var body: some View { TabView { FirstTabView() .tabItem { Label("Tab 1", systemImage: "house") } SecondTabView() .tabItem { Label("Tab 2", systemImage: "star") } } } } struct FirstTabView: View { @State private var text = "" var body: some View { NavigationStack { VStack { TextField("Enter something 1", text: $text) .textFieldStyle(RoundedBorderTextFieldStyle()) .padding() } .toolbar { ToolbarItemGroup(placement: .keyboard) { Button("Done") { UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) } } } } } } struct SecondTabView: View { @State private var text = "" var body: some View { NavigationStack { VStack { TextField("Enter something 2", text: $text) .textFieldStyle(RoundedBorderTextFieldStyle()) .padding() } .toolbar { ToolbarItemGroup(placement: .keyboard) { Button("Done") { UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) } } } } } } #Preview { MainTabView() }
0
1
167
Sep ’24
run Http in webview local
hi, i have this problem. i need to use a webview to charge a file locally, to be more specific a file SCORM, like a mini web project. so i was making tests and the way to see all te content is in a http server. i mean if i click in the index.html of the file in my computer the page doesn't charge all the content, so i opened visual studio code and running Live Server thats provide me a project in http, well with that the project works. in android i'm make the example with something called WebViewAssetLoader, with that i can setup asset loader to handle local asset paths and override a WebView client, and if request is to local file, intercept and serve local. i want to know if in swift i have a way to intecept it a serve local this is one of the a lot of ways that i was tried and this is the example that works for me in android
2
0
259
Sep ’24
How to generate thumbnails for protected content using AVAssetImageGenerator?
I have a FairPlay-encrypted HLS stream and played the video in an AVPlayer.And I want to generate scrubbing thumbnails using the AVAssetImageGenerator. Also, I am able to generate thumbnails for clear streams but get errors for protected content. *How to generate thumbnails for protected content. func getImageThumbnail(forTime: CMTime) { let generator = AVAssetImageGenerator(asset: asset) generator.appliesPreferredTrackTransform = true generator.cancelAllCGImageGeneration() generator.generateCGImagesAsynchronously(forTimes: [NSValue(time: forTime)]) { [weak self] requestedTime, image, actualTime, result, error in if let error = error { print("Error generate: \(error.localizedDescription)") return } if let image = image { DispatchQueue.main.async { let image = UIImage(cgImage: image).jpegData(compressionQuality: 1.0) self?.playerImg.image = UIImage(data: image!) } } } }
1
0
301
Sep ’24
SwiftUI [[stichable]] metal shader & CIFilter written in metal extern"C" can't work at the same time
In my project, I used two metal shaders in two ways. One is link to SwiftUI's modifier .colorEffect(ShaderLibrary.myShader()), which metal shader marked as [[stichable]]. Another one is a custom CIFilter, which kernel been written in external "C" closure. Because custom CIFilter must add build rules so Xcode can compile it, so I added -fcikernel to Metal Compiler and -cikernel to Metal Linker from Build Settings, just like Apple's document told me that. But the result is weird, if I add rules, custom CIFilter works, [[stichable]] shader doesn't work. if I delete rules, and comment out code of CIFilter(for avoiding warning), [[stichable]] shader works, but now I can't use my custom CIFilter. Actually, once these two shaders works well in my project, but when I updated Xcode from 15 to 16, it became weird, the 2 shaders can't exist at same time. Even though I go back to Xcode 15, I can't save them. I have no idea, please help, thank you. XCode 16 / iOS 18 on iPhone 14 Pro
2
0
365
Sep ’24
Issues with Handling URL Schemes and App State Transitions in iOS App
I'm working on an iOS app that integrates with Spotify for authentication. I’m facing a problem where the app doesn’t handle URL schemes and app state transitions properly. Specifically, when Spotify redirects back to my app, it either doesn’t handle the URL correctly or doesn’t transition between states as expected. The authorization for spotify is successful, then my app reopens and nothing happens after that. Expected Behavior: When Spotify redirects to my app, it should correctly handle the URL and process authentication parameters. Actual Behavior: Even with URL handling code commented out, the app reopens from Spotify, which suggests a possible issue with how URL schemes or app state transitions are managed. The app’s state transitions don’t seem to be handled as expected. Troubleshooting Steps Taken: Verified URL schemes and redirect URIs. Implemented application(_:open:options:) for URL handling. Tested various app states (foreground, background, suspended). //This code should open my app using the URL from spotify but this code never triggers and yet my app opens anyways// func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { print("Received URL: (url.absoluteString)") handleSpotifyURL(url) return true } private func handleSpotifyURL(_ url: URL) { // URL handling logic } func applicationDidBecomeActive(_ application: UIApplication) { // Logic for when the app becomes active } //Using latest software for xcode, testing on iphone 14 with up to date software and up to date spotify As mentioned - have ensure that my info plist is configured correctly, that spotify authorizes correctly, that the redirect URI is correct in my code and on spotify for developers. From the testing I've done I imagine there is something wrong with how my app gets opened vs how it should get opened with the callback URL triggering func application(_ app: UIApplication, open url: URL, options:.... What I am expecting is that when spotify triggers the callback url - my app reopens with the above function and from there can retrieve the access token etc.
0
0
287
Sep ’24
Swift 6 Migration error in Sample code (Updating an app to use strict concurrency sample code) provided by Apple.
Updating an app to use strict concurrency is not compiling in Swift 6 with strict concurrency enabled. I am getting the following error in Xcode Version 16.0 (16A242d). private func queryHealthKit() async throws -&gt; ( [HKSample]?, [HKDeletedObject]?, HKQueryAnchor? ) { try await withCheckedThrowingContinuation { continuation in // Create a predicate that returns only samples created within the last 24 hours. let endDate = Date() let startDate = endDate.addingTimeInterval(-24.0 * 60.0 * 60.0) let datePredicate = HKQuery.predicateForSamples( withStart: startDate, end: endDate, options: [.strictStartDate, .strictEndDate]) // Create the query. let query = HKAnchoredObjectQuery( type: caffeineType, predicate: datePredicate, anchor: anchor, limit: HKObjectQueryNoLimit ) { (_, samples, deletedSamples, newAnchor, error) in // When the query ends, check for errors. if let error { continuation.resume(throwing: error) } else { continuation.resume(returning: (samples, deletedSamples, newAnchor)) } } store.execute(query) } } The error is on ** continuation.resume(returning: (samples, deletedSamples, newAnchor)) ** and the error is Task-isolated value of type '([HKSample]?, [HKDeletedObject]?, HKQueryAnchor?)' passed as a strongly transferred parameter; later accesses could race. How to solve this error?
2
1
666
Sep ’24
Upgrade to XCode 16. Undefined symbol: nominal type descriptor for CoreGraphics.CGFloat
ld: symbol(s) not found for architecture arm64 clang++: error: linker command failed with exit code 1 (use -v to see invocation) Undefined symbol: nominal type descriptor for CoreGraphics.CGFloat Undefined symbol: type metadata for CoreGraphics.CGFloat Undefined symbol: protocol conformance descriptor for CoreGraphics.CGFloat : Swift.BinaryFloatingPoint in CoreGraphics Undefined symbol: protocol conformance descriptor for CoreGraphics.CGFloat : Swift.Encodable in CoreGraphics Undefined symbol: protocol conformance descriptor for CoreGraphics.CGFloat : Swift.FloatingPoint in CoreGraphics Undefined symbol: protocol conformance descriptor for CoreGraphics.CGFloat : Swift.Hashable in CoreGraphics Undefined symbol: protocol conformance descriptor for CoreGraphics.CGFloat : Swift.Comparable in CoreGraphics Undefined symbol: protocol conformance descriptor for CoreGraphics.CGFloat : Swift.Equatable in CoreGraphics Undefined symbol: protocol conformance descriptor for CoreGraphics.CGFloat : Swift.Decodable in CoreGraphics Undefined symbol: protocol conformance descriptor for CoreGraphics.CGFloat : Swift.SignedNumeric in CoreGraphics
3
2
1.4k
Sep ’24
JSONEncoder: How to sort keys using "localizedStandardCompare"? (just like how Xcode 16 serialize a xcstrings file)
Hello, I'd like to ask a very fundamental question about JSONEncoder: how to sort keys in a specific order when encoding a dictionary to JSON text? I know there is an option called JSONEncoder.OutputFormatting.sortedKeys, but it sorts the keys only in lexicographic order. I want to sort the keys using a different comparator, such as String.localizedStandardCompare(_:), which achieves the "Finder-like" order. The reason why I ask this question is because I have a localization tool that works with String Catalog (xcstrings file, which is a JSON), but every time my tool serializes an xcstrings file, it always messes up the keys in lexicographic order (I used JSONEncoder + .sortedKeys). Meanwhile, Xcode 16 always serializes the string keys into the "Finder-like" order. As a result, my tool always generates a huge diff when manipulating the xcstrings even when making only a small modification to it. So I am wondering how Xcode 16 implements the String Catalog tool to serialize the JSON in "Finder-like" order. It would be great if JSONEncoder could do that too. Or, maybe I can use another serialization method to implement this behavior?
4
0
467
Sep ’24