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

Document and data size in ios
We want to give the user the ability to clear "document and data". We first try to calculate the size by summing the size of all the files in that directory FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first. But after calculating the size, we see that the size of the "document and data" that the user sees in the storage is larger than the size of our cache in ios 17. But in earlier versions 16, 15, etc. this directory is not taken into account when calculating the size . Which directories are counted in ios 17? And what directories are taken into account in an earlier version of iOS?
0
0
38
12h
UIAccessibility.Notification concurrency errors with Xcode 16 beta 2
I am running into some Swift 6 concurrency errors that I think are due to an odd oversight in the UIAccessibility Swift interface. There are a number of constants defined in here for various things, most of which are marked "let" (appropriately). However, the constants for notifications in extension UIAccessibility.Notification are all marked as var for some reason. For example: public static var pageScrolled: UIAccessibility.Notification Because it is var, not let, anytime I try to access it, I get a concurrency violation. I am baffled as to how I am supposed to work around this. For example, this line of code: UIAccessibility.post(notification: .pageScrolled, argument: "test") gives the error: "Reference to static property 'pageScrolled' is not concurrency-safe because it involves shared mutable state" I can't for the life of me figure out how to work around this. I guess maybe define my own constant somewhere and suss out the rawValue somehow for now? This really needs to be fixed in the SDK.
4
0
66
10h
Screen Sleep Issue When Removing Vision Pro
Hello VisionOS Developer Community, I am currently working on a demo application for VisionOS, tailored for the Vision Pro. In my application, I have implemented a feature to prevent the screen from sleeping using the following code: UIApplication.shared.isIdleTimerDisabled = true This works perfectly on iOS, ensuring the screen remains active regardless of other system settings. However, I've run into a snag with VisionOS. Even with isIdleTimerDisabled set to true, the screen still sleeps when I take off the Vision Pro.
0
0
18
18h
Swift FileManager.default.copyItem(at: URL, to: URL) folder permission error
I'm working on creating a tiny app that copies a random sampling of files from a source folder to a destination folder: https://github.com/belovachap/Select-Random-Files-Mac I choose folders in my user's Documents folder, am able to get the random sampling of files but then run into permission errors when trying to copy to the destination folder. I've tried adding a call to startAccessingSecurityScopedResource on the destination URL but it doesn't seem to help. Is this having the same problems on anyone else's computer??
1
0
55
1d
Seeking guidance on intercepting system-wide notifications in macOS app
I'm developing a macOS application called Blurt, which aims to provide enhanced notification management in MacOS. The core functionality I'm trying to implement is the ability to intercept and display notifications from various applications in a custom interface. Current implementation: Using AppDelegate to handle application lifecycle Implemented UNUserNotificationCenterDelegate for handling notifications Created a custom NotificationService extension Challenges: Unable to intercept notifications from other applications System notifications are not being captured by our app What I've tried: Using DistributedNotificationCenter to observe system-wide notifications Implementing a Notification Service Extension Exploring NSWorkspace notifications Current roadblocks: Apple's sandboxing and security model seems to prevent direct access to other apps' notifications Unable to find a sanctioned API for system-wide notification interception Questions: Is there a recommended approach to creating a centralized notification management system within Apple's guidelines? Are there any specific system notifications or events we can legally subscribe to that might help achieve similar functionality? How do other notification management apps (if any exist) handle this limitation? Are there any upcoming APIs or features in macOS that might address this use case? I'm open to alternative approaches or pivoting the app's functionality if necessary. Any insights, suggestions, or resources would be greatly appreciated. Thank you in advance for your help!
1
0
98
12h
Peculiar EXC_BAD_ACCESS, involving sparse matrices
Helo all, Currently, I'm working on an iOS app that performs measurement and shows the results to the user in a graph. I use a Savitzky-Golay filter to filter out noise, so that the graph is nice and smooth. However, the code that calculates the Savitzky-Golay coefficients using sparse matrices crashes sometimes, throwing an EXC_BAD_ACCESS. I tried to find out what the problem is by turning on Address Sanitizer and Thread Sanitizer, but, for some reason, the bad access exception isn't thrown when either of these is on. What else could I try to trace back the problem? Thanks in advance, CaS To reproduce the error, run the following: import SwiftUI import Accelerate struct ContentView: View { var body: some View { VStack { Button("Try", action: test) } .padding() } func test() { for windowLength in 3...100 { let coeffs = SavitzkyGolay.coefficients(windowLength: windowLength, polynomialOrder: 2) print(coeffs) } } } class SavitzkyGolay { static func coefficients(windowLength: Int, polynomialOrder: Int, derivativeOrder: Int = 0, delta: Int = 1) -> [Double] { let (halfWindow, remainder) = windowLength.quotientAndRemainder(dividingBy: 2) var pos = Double(halfWindow) if remainder == 0 { pos -= 0.5 } let X = [Double](stride(from: Double(windowLength) - pos - 1, through: -pos, by: -1)) let P = [Double](stride(from: 0, through: Double(polynomialOrder), by: 1)) let A = P.map { exponent in X.map { pow($0, exponent) } } var B = [Double](repeating: 0, count: polynomialOrder + 1) B[derivativeOrder] = Double(factorial(derivativeOrder)) / pow(Double(delta), Double(derivativeOrder)) return leastSquaresSolution(A: A, B: B) } static func leastSquaresSolution(A: [[Double]], B: [Double]) -> [Double] { let sparseA = A.sparseMatrix() var sparseAValuesCopy = sparseA.values var xValues = [Double](repeating: 0, count: A.transpose().count) var bValues = B sparseAValuesCopy.withUnsafeMutableBufferPointer { valuesPtr in let a = SparseMatrix_Double( structure: sparseA.structure, data: valuesPtr.baseAddress! ) bValues.withUnsafeMutableBufferPointer { bPtr in xValues.withUnsafeMutableBufferPointer { xPtr in let b = DenseVector_Double( count: Int32(B.count), data: bPtr.baseAddress! ) let x = DenseVector_Double( count: Int32(A.transpose().count), data: xPtr.baseAddress! ) #warning("EXC_BAD_ACCESS is thrown below") print("This code is executed...") let status = SparseSolve(SparseLSMR(), a, b, x, SparsePreconditionerDiagScaling) print("...but, if an EXC_BAD_ACCESS is thrown, this code isn't") if status != SparseIterativeConverged { fatalError("Failed to converge. Returned with error \(status).") } } } } return xValues } } func factorial(_ n: Int) -> Int { n < 2 ? 1 : n * factorial(n - 1) } extension Array where Element == [Double] { func sparseMatrix() -> (structure: SparseMatrixStructure, values: [Double]) { let columns = self.transpose() var rowIndices: [Int32] = columns.map { column in column.indices.compactMap { indexInColumn in if column[indexInColumn] != 0 { return Int32(indexInColumn) } return nil } }.reduce([], +) let sparseColumns = columns.map { column in column.compactMap { if $0 != 0 { return $0 } return nil } } var counter = 0 var columnStarts = [Int]() for sparseColumn in sparseColumns { columnStarts.append(counter) counter += sparseColumn.count } let reducedSparseColumns = sparseColumns.reduce([], +) columnStarts.append(reducedSparseColumns.count) let structure: SparseMatrixStructure = rowIndices.withUnsafeMutableBufferPointer { rowIndicesPtr in columnStarts.withUnsafeMutableBufferPointer { columnStartsPtr in let attributes = SparseAttributes_t() return SparseMatrixStructure( rowCount: Int32(self.count), columnCount: Int32(columns.count), columnStarts: columnStartsPtr.baseAddress!, rowIndices: rowIndicesPtr.baseAddress!, attributes: attributes, blockSize: 1 ) } } return (structure, reducedSparseColumns) } func transpose() -> Self { let columns = self.count let rows = self.reduce(0) { Swift.max($0, $1.count) } return (0 ..< rows).reduce(into: []) { result, row in result.append((0 ..< columns).reduce(into: []) { result, column in result.append(row < self[column].count ? self[column][row] : 0) }) } } }
10
0
123
16h
Getting the amount of audio loaded in an AVPlayer
I have AVPlayer loading an MP3 from a URL. While it is playing, how can I tell how much of the MP3 has been actually downloaded so far? I have tried using item.loadedTimeRanges, but it does not seem to be accurate. I get a few notifications but it usualy stops sending notifications around 80 seconds and doesn't keep up to even the current position of the player. Any idea? Also, is there any way to get the total duration of the audio? All the methods I've tried return NAN.
0
0
87
3d
What is the info property of SwiftUI::Layer
What is the info property of SwiftUI::Layer? I couldn't find any document or resource about it. It appears in SwiftUI::Layer's definition: struct Layer { metal::texture2d<half> tex; float2 info[5]; /// Samples the layer at `p`, in user-space coordinates, /// interpolating linearly between pixel values. Returns an RGBA /// pixel value, with color components premultipled by alpha (i.e. /// [R*A, G*A, B*A, A]), in the layer's working color space. half4 sample(float2 p) const { p = metal::fma(p.x, info[0], metal::fma(p.y, info[1], info[2])); p = metal::clamp(p, info[3], info[4]); return tex.sample(metal::sampler(metal::filter::linear), p); } };
0
1
151
3d
Swift Syntax Comment Trivia - Expected prefixes
Hello! I am working on a project that does some automatic code generation using SwiftSyntax and SwiftSyntaxBuilder. As part of this project, I want to put in a comment at the top of the file warning users to not modify the file and make it obvious that the code was automatically generated. I was trying to use the .lineComment(String) static member of the Trivia (or TriviaPiece) types and I expected that the comment would automatically be prefixed with the expected // and space for use in code. (For example, Trivia.lineComment("No comment") would be written as // No Comment when sent through a BasicFormat Object or similar SyntaxRewriter). I was surprised to find that this is not the case and was wondering before I write an issue on GitHub whether this behavior is intentional or a bug. If it is intentional, I'm not entirely sure if I'm missing something regarding this to more easily generate these comments. At the moment my comment generation consists of constructing the comment in the leadingTrivia of the syntax node that appears after the comment. For example: VariableDeclSyntax(leadingTrivia: [.newlines(2), .lineComment("// These members are always generated irrespective of the contents of the generated files. They are intended to exclusively centralize code symbols that would otherwise be repeated frequently."), .newlines(1)], modifiers: [DeclModifierSyntax(name: .keyword(.private)), DeclModifierSyntax(name: .keyword(.static))], .let, name: PatternSyntax(IdentifierPatternSyntax(identifier: "decoder")), initializer: InitializerClauseSyntax(value: ExprSyntax(stringLiteral: "\(configuration.decoderExpression)"))) outputs // These members are always generated irrespective of the contents of the generated files. They are intended to exclusively centralize code symbols that would otherwise be repeated frequently. private static let decoder = JSONDecoder() in this project (with example data having been added).
0
0
108
4d
Question About Weak Self Usage
Hello everyone. I have a small question about Weak Self. In the example below, I am doing a long process to the data I query with SwiftData. (For this reason, I do it in the background.) I don't know if there is a possibility of a memory leak when the view is closed because this process takes a long time. import SwiftUI import SwiftData struct ActiveRegView: View { @Query(filter: #Predicate<Registration> { $0.activeRegistration }, animation: .default) private var regs: [Registration] @Environment(ViewModel.self) private var vm @State private var totalParkingFee: Decimal = 0 var body: some View { ... .onAppear { var totalParkingFee = Decimal() DispatchQueue.global(qos: .userInitiated).async { for reg in regs { totalParkingFee += vm.parkingFee(from: reg.entryRegistration.entryDate, to: .now, category: reg.category, isCustomPrice: reg.isCustomPrice) } DispatchQueue.main.async { withAnimation { totalParkingFee = totalParkingFee } } } } } } I use ViewModel with @Environment, so I don't initilize ViewModel every time view is initilized. I know it's a simple question and I thank you in advance for your answers.
0
0
65
4d
UIKit MacCatalyst - How to drag a table view item to Finder to create a folder of items
I have a UITableView that displays a Group/Note hierarchy analogous to a Finder Folder/Files hierarchy. I have implemented Drag and Drop such that if I drag a Note to the Finder Desktop an HTML file is created of the Note, and if I drag a Group to the Finder Desktop a Text file is created of the Group's title. Here is the Helper Dragging extension that I've implemented: // // Model+Dragging.swift // /* Abstract: Helper methods for providing and consuming drag-and-drop data. */ import UIKit import MobileCoreServices // Conditionalize Drag and Drop so it is not in iOS target. #if targetEnvironment(macCatalyst) extension Model { /** A helper function that serves as an interface to the data model, called by the implementation of the `tableView(_ canHandle:)` method. */ func canHandle(_ session: UIDropSession) -> Bool { // In order to enable dragging all text type files changed the class // loadable objects from NSString to my custom TEXTClass. return session.canLoadObjects(ofClass: TEXTClass.self) } /** A helper function that serves as an interface to the data model, called by the `tableView(_:itemsForBeginning:at:)` method. */ func dragItems(for indexPath: IndexPath) -> [UIDragItem] { let itemProvider = NSItemProvider() let item = self.getDisplayItem(for: indexPath.row) if item is Note { let note:Note = item as! Note let html = note.noteHTML let data = html?.data(using: .utf8) // Drag to finder creates an html file. itemProvider.suggestedName = note.title + ".html" itemProvider.registerDataRepresentation(forTypeIdentifier: kUTTypeData as String, visibility: .all) { completion in completion(data, nil) return nil } } else { let group:Group = item as! Group let title = group.title let data = title?.data(using: .utf8) // Drag to finder creates a text file. itemProvider.suggestedName = group.title + ".text" itemProvider.registerDataRepresentation(forTypeIdentifier: kUTTypeData as String, visibility: .all) { completion in completion(data, nil) return nil } } return [ UIDragItem(itemProvider: itemProvider) ] } } #endif I would now like to change the result of dragging a Group to the Finder. Instead of creating a Text file from the drag data, I would like to create a Folder containing the Group's Notes. Note: I am unconcerned with the task of assembling the Group/Notes hierarchies as Folder/Files hierarchies because I already have implemented such previously as a menu export command. My concern is where and how I can communicate it to the Finder in the Drag and Drop process. As a first step I thought I would simply create an empty folder from the drag of a Group. So far, none of my experiments have been successful. Every variation of itemProvider.registerDataRepresentation(forTypeIdentifier: or itemProvider.registerFileRepresentation(forTypeIdentifier: or registerItem(forTypeIdentifier:loadHandler: that I have tried has failed to produce anything but empty TEXT files, if they worked at all. It is my understanding that itemProviders may provide directories instead of files, but I have been unable to find any examples of such. My problem may be a lack of understanding of the syntax and usage of the NSItemProvider.LoadHandler completion block. Any Swift examples on point would be greatly appreciated!
0
0
64
4d
iOS Push to Talk Framework Not Working in Archive Build (Flutter)
I have developed an app using Flutter that utilizes the Push to Talk framework on iOS. The Push to Talk feature works perfectly in debug mode, but after archiving the build and installing it on an iOS 17 device, the Push to Talk functionality stops working. Here are the steps I have already taken: Enabled background modes. Enabled Push to Talk capabilities. Despite these settings, the issue persists in the archive build. Has anyone else encountered this issue? What additional steps or configurations are required to get Push to Talk working in the archive build on iOS 17? Any help or guidance would be greatly appreciated. Thank you!
1
0
113
5d
"Planning swift module" takes several minutes
Hi, I'm looking for help on how to troubleshoot. I will probably file a bug report, but I wonder if it's Xcode or Swift, and I would like to put some more data than I currently have. With Xcode 16 beta 2, the "planning swift module" stage of one of the modules often takes several minutes (between 280 and 300 seconds). Normally it takes a few seconds. The other modules take less than a second. I have a workspace, containing a project and 3 local swift packages. My project contains one iOS app target, 1 framework target (a dependency of the app), and several test targets. The faulty module is the app module.
0
0
46
5d
Automatic Grammar Agreement with formatted number: use integer value to switch categories
Hello, I want to use Automatic Grammar Agreement to localise a string in my app, let say "three remaining activities". The string "three" is obtained by using a NumberFormatter with a numberStyle set to .spellOut (so I'm not using an Integer) var formatter: NumberFormatter = NumberFormatter() formatter.numberStyle = .spellOut let formattedCount: String = numberFormatter.string(from: count as NSNumber)! Text("key_with_string_\(formattedCount)") In my string catalog, I have translated the key key_with_string_%@ like this ^[%@ remaining activity](inflect: true), but it does not work. I've tried to add the integer value used by the number formatter in the key key_with_string_%@_%lld but it does not work. Should Automatic Grammar Agreement work normally just by using the formatted string provided by the NumberFormatter? If not, is there a way to specify to use a secondary variable (my count integer) to switch between different categories like one and other automatically? Thanks ! Axel
1
0
112
5d
Issue with Swift and C++ Interoperability: Passing void pointer between Swift and C++
Hello everyone, I'm encountering an issue with Swift and C++ interoperability when passing a void pointer between Swift and C++ functions. When I pass pMessageBuffer (an UnsafeMutableRawPointer) from Swift to MyCppClass.NFCompletion (a static c++ function), which expects a reference to void pointer, Swift throws an error "Cannot convert value of type 'UnsafeMutableRawPointer' to expected argument type 'Optional' ". Here is a sample code to help in better visualization of the usecase. Cpp Code class MyCppClass { public: static void SendData(void *pMessage, TUInt16 pMessageLength) { // Assume vSocket is my Swift object held in C++. vSocket.Send(pMessage, pMessageLength); } static void NFCompletion(void * & pBuffer, TInt64 pErrorCode, VPtr pCompletionFunction) { // Process the buffer. } }; Swift Code: public class MySwiftClass { var vConnection: NWConnection? public init() {} public func Send(_ pMessageBuffer: UnsafeMutableRawPointer, _ pMessageLength: TSUInt16) { let messageData = Data(bytesNoCopy: pMessageBuffer, count: Int(pMessageLength), deallocator: .none) self.vConnection?.send(content: messageData, completion: .contentProcessed { nw_error in var error_code: TSInt64 = 0 if let nw_error = nw_error { error_code = self.InternalGetNetworkErrorCode(nw_error) } // Here's where the issue arises: MyCppClass.NFCompletion(pMessageBuffer, TInt64(error_code), self.uCompletionHandler) }) } // Example function to handle network errors private func InternalGetNetworkErrorCode(_ error: Error) -> TSInt64 { // Implementation to convert nw_error to TSInt64 error code return 0 // Placeholder return value } } Could someone please help me understand why this conversion error occurs? How should I correctly handle passing a void pointer between Swift and C++ functions, ensuring compatibility and proper memory management? Note: TSInt64 is typealias for swift Int and TInt64 is alias of c++ int_64t. Thank you in advance for your assistance! Regards, Harshal
0
1
91
5d
How to migrate PHPhotoLibraryChangeObserver to Swift 6?
I have the following code: extension AssetGridViewController: PHPhotoLibraryChangeObserver { func photoLibraryDidChange(_ changeInstance: PHChange) { Task { @MainActor in guard let changes = changeInstance.changeDetails(for: fetchResult) else { return } fetchResult = changes.fetchResultAfterChanges } } } With Swift 6, this generates a compilation error: Main actor-isolated instance method 'photoLibraryDidChange' cannot be used to satisfy nonisolated protocol requirement. The error includes to fix-it suggestions: Adding nonisolated to the function (nonisolated func photoLibraryDidChange(_ changeInstance: PHChange)) Adding @preconcurrency to the protocol conformance (extension AssetGridViewController: @preconcurrency PHPhotoLibraryChangeObserver {) Both options generate a runtime error: EXC_BREAKPOINT (code=1, subcode=0x105b7c400). For context, AssetGridViewController is a regular UIViewController. Any ideas on how to fix this?
1
0
103
6d