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

Phone app and CallDirectory
Prior to iOS18, the incoming/outgoing call history display in the Phone app matched the CallDirectory content, but starting with iOS18, changing the information tied to the same number results in the incoming/outgoing call history not matching the CallDirectory content, as it remains unchanged before the change. Is this a strongly intended change? If not, we would like to have it reverted back to the way it worked before iOS18. Befor iOS18 Register the target phone number and name1 to CallRirectory Incoming call using the target phone number The target phone number and name1 is recorded as an incoming call history Register the target phone number and name2 to CallRirectory Incoming call using the target phone number again The target phone number and name2 is recorded as an incoming call history Also 1st incoming call history’s name is changed to name2 After iOS18 Register the target phone number and name1 to CallRirectory Incoming call using the target phone number The target phone number and name1 is recorded as an incoming call history Register the target phone number and name2 to CallRirectory Incoming call using the target phone number again The target phone number and name2 is recorded as an incoming call history But 1st incoming call history’s name is still name1 Why does this difference occur?
0
0
6
32m
Launch screen more vibrant in iOS18?
Hi! I've detected that in iOS18 launch screen colors differs from the defined ones, that is, if I create a launch screen with a color like #ff0000 (red) and the initial view controller is a view controller with the same color as background, I can see the transition between launch screen and the initial view controller because the launch screen color is different from the other one (dark in this case). I've tested it with several colors: left side is the launch screen and right side is the initial view controller. Both views created with IB using the same colors (it also happens with background images using colors) Is this an intentionall behavior? If so, theres a way to disable it? I need the transition between the launch screen and my initial view controller to be non perceptible... Thanks!
4
1
87
7h
Why personal music recommendations contain no more than 12 item?
Hi! I get personal recommendations MusicItemCollection using this code: func getRecommendations() async throws -> MusicItemCollection<MusicPersonalRecommendation> { let request = MusicPersonalRecommendationsRequest() let response = try await request.response() let recommendations = response.recommendations return recommendations } However, all recommendations contain no more than 12 MusicItem's, while the Music.app application provides much more for some recommendations, for example, for the You recently listened recommendation, the Music.app application displays 40 items. Each recommendation has an items property that contains a collection of musical items MusicItemCollection<MusicPersonalRecommendation.Item>, the hasNextBatch property for these collections is always false. I expected that for some collections loading of new items would be available. Please tell me if I'm doing something wrong or is this a MusicKit bug? Thank you!
0
0
101
2d
Not able to save with SwiftData. "The file “default.store” couldn’t be opened."
I get this message when trying to save my Models. CoreData: error: SQLCore dispatchRequest: exception handling request: <NSSQLSaveChangesRequestContext: 0x303034540> , I/O error for database at /var/mobile/Containers/Data/Application/726ECA8C-6C67-4BFE-89E7-AFD8A83CAA5D/Library/Application Support/default.store. SQLite error code:1, 'no such table: ZCALENDARMODEL' with userInfo of { NSFilePath = "/var/mobile/Containers/Data/Application/726ECA8C-6C67-4BFE-89E7-AFD8A83CAA5D/Library/Application Support/default.store"; NSSQLiteErrorDomain = 1; } SwiftData.DefaultStore save failed with error: Error Domain=NSCocoaErrorDomain Code=256 "The file “default.store” couldn’t be opened." UserInfo={NSFilePath=/var/mobile/Containers/Data/Application/726ECA8C-6C67-4BFE-89E7-AFD8A83CAA5D/Library/Application Support/default.store, NSSQLiteErrorDomain=1} The App has Recipes and Calendars and the user can select a Recipe for each Calendar day. The recipe should not be referenced, it should be saved by SwiftData along with the Calendar. import SwiftUI import SwiftData enum CalendarSource: String, Codable { case created case imported } @Model class CalendarModel: Identifiable, Codable { var id: UUID = UUID() var name: String var startDate: Date var endDate: Date var recipes: [String: RecipeData] = [:] var thumbnailData: Data? var source: CalendarSource? // Computed Properties var daysBetween: Int { let days = Calendar.current.dateComponents([.day], from: startDate.midnight, to: endDate.midnight).day ?? 0 return days + 1 } var allDates: [Date] { startDate.midnight.allDates(upTo: endDate.midnight) } var thumbnailImage: Image? { if let data = thumbnailData, let uiImage = UIImage(data: data) { return Image(uiImage: uiImage) } else { return nil } } // Initializer init(name: String, startDate: Date, endDate: Date, thumbnailData: Data? = nil, source: CalendarSource? = .created) { self.name = name self.startDate = startDate self.endDate = endDate self.thumbnailData = thumbnailData self.source = source } // Convenience initializer to create a copy of an existing calendar static func copy(from calendar: CalendarModel) -> CalendarModel { let copiedCalendar = CalendarModel( name: calendar.name, startDate: calendar.startDate, endDate: calendar.endDate, thumbnailData: calendar.thumbnailData, source: calendar.source ) // Copy recipes copiedCalendar.recipes = calendar.recipes.mapValues { $0 } return copiedCalendar } // Codable Conformance private enum CodingKeys: String, CodingKey { case id, name, startDate, endDate, recipes, thumbnailData, source } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) id = try container.decode(UUID.self, forKey: .id) name = try container.decode(String.self, forKey: .name) startDate = try container.decode(Date.self, forKey: .startDate) endDate = try container.decode(Date.self, forKey: .endDate) recipes = try container.decode([String: RecipeData].self, forKey: .recipes) thumbnailData = try container.decodeIfPresent(Data.self, forKey: .thumbnailData) source = try container.decodeIfPresent(CalendarSource.self, forKey: .source) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(id, forKey: .id) try container.encode(name, forKey: .name) try container.encode(startDate, forKey: .startDate) try container.encode(endDate, forKey: .endDate) try container.encode(recipes, forKey: .recipes) try container.encode(thumbnailData, forKey: .thumbnailData) try container.encode(source, forKey: .source) } } import SwiftUI struct RecipeData: Codable, Identifiable { var id: UUID = UUID() var name: String var ingredients: String var steps: String var thumbnailData: Data? // Computed property to convert thumbnail data to a SwiftUI Image var thumbnailImage: Image? { if let data = thumbnailData, let uiImage = UIImage(data: data) { return Image(uiImage: uiImage) } else { return nil // No image } } init(recipe: RecipeModel) { self.name = recipe.name self.ingredients = recipe.ingredients self.steps = recipe.steps self.thumbnailData = recipe.thumbnailData } } import SwiftUI import SwiftData @Model class RecipeModel: Identifiable, Codable { var id: UUID = UUID() var name: String var ingredients: String var steps: String var thumbnailData: Data? // Store the image data for the thumbnail static let fallbackSymbols = ["book.pages.fill", "carrot.fill", "fork.knife", "stove.fill"] // Computed property to convert thumbnail data to a SwiftUI Image var thumbnailImage: Image? { if let data = thumbnailData, let uiImage = UIImage(data: data) { return Image(uiImage: uiImage) } else { return nil // No image } } // MARK: - Initializer init(name: String, ingredients: String = "", steps: String = "", thumbnailData: Data? = nil) { self.name = name self.ingredients = ingredients self.steps = steps self.thumbnailData = thumbnailData } // MARK: - Copy Function func copy() -> RecipeModel { RecipeModel( name: self.name, ingredients: self.ingredients, steps: self.steps, thumbnailData: self.thumbnailData ) } // MARK: - Codable Conformance private enum CodingKeys: String, CodingKey { case id, name, ingredients, steps, thumbnailData } required init(from decoder: Decoder) throws { ... } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(id, forKey: .id) try container.encode(name, forKey: .name) try container.encode(ingredients, forKey: .ingredients) try container.encode(steps, forKey: .steps) try container.encode(thumbnailData, forKey: .thumbnailData) } }
0
0
113
2d
[Xcode:BuildSettings] Keep some warnings as warnings while the rest as errors
We have a big iOS project and we are using .xcconfig files to define our compiler options and build settings. We have our SWIFT_TREAT_WARNINGS_AS_ERRORS set to YES so that all Swift related warnings will be reported as errors. Now, we are trying to migrate to Xcode 16.1 and set 'targeted' in the 'Strict Concurrency Checking' flag. This produces some errors that are related to Swift's concurrency checks. We are now planning to have an approach where we still want to keep SWIFT_TREAT_WARNINGS_AS_ERRORS as is but we want all concurrency related warnings to be still treated as warnings while the rest will get reported as errors. We found this new compiler option - https://forums.swift.org/t/warnings-as-errors-exceptions/72925. It looks like the one we want but I think it is still not out yet and we need to wait until Swift 6.1 (correct me if im wrong). Or is there any other way to do what we want to achieve?
0
0
48
3d
SceneView selective draw since concurrency
I have used SceneKit for several years but recently have a problem where a scene with fewer than 50 nodes is partially drawn, i.e., some nodes are, some aren't, and greater than 50 nodes are always draw correctly. This seems to have happened since concurrency was introduced. (w.r.t. concurrency, I had been using DispatchQueue successfully before then.) Since all nodes (few or many) are constructed and implemented by the same functions etc. I'm baffled. When I print the node hierarchy all nodes are present whether few or many. SceneView() has [.rendersContinually] option selected. Every node created (few or many) has .opacity = 1.0, .isHidden = false I haven't tried setting-back the compiler version as that is not a long term solution, and I know the same code worked fine then.
6
0
130
3d
Swift6 race warning
I'm trying to fix some Swift6 warnings, this one seems too strict, I'm not sure how to fix it. The variable path is a String, which should be immutable, it's a local variable and never used again inside of the function, but still Swift6 complains about it being a race condition, passing it to the task What should I do here to fix the warning?
4
0
130
3d
Ability to retrieve keychain item appears to be lost after restoring an IOS Device
On some production devices our application fails to find the keychain item associated with our application where we store our JWT tokens. We have been unable to reproduce this in house for many months. Today I restored a phone from a backup using the device to device transfer of data as I replaced my personal phone. On that device now when opened each time I am prompted to login again and it appears my token is never saved to the keychain. Upon every successive reopen of the application I see this error in the console. Error fetching keychain item - Error Domain=NSOSStatusErrorDomain Code=-25300 "no matching items found" UserInfo={numberOfErrorsDeep=0, NSDescription=no matching items found} I currently do not see any errors in the console related to the saving of said token. We access this token with the after first unlock security and we do not allow iCloud backup for these tokens. Any help here would be appreciated. I'm not sure what would cause an issue like this. Other applications on my device do not seem to have this issue, so Its likely something we're doing code wise that may be different. Any hints as to what to look for here may be of help. The previous device or any device i have not created from a backup works as intended, including about 95% of our production users.
4
2
117
3d
Writing an `NWProtocolFramerImplementation` to run on top of `NWProtocolWebSocket`
Hi All, I am trying to write an NWProtocolFramerImplementation that will run after Websockets. I would like to achieve two goals with this Handle the application-layer authentication handshake in-protocol so my external application code can ignore it Automatically send pings periodically so my application can ignore keepalive I am running into trouble because the NWProtocolWebsocket protocol parses websocket metadata into NWMessage's and I don't see how to handle this at the NWProtocolFramerImplementation level Here's what I have (see comments for questions) class CoolProtocol: NWProtocolFramerImplementation { static let label = "Cool" private var tempStatusCode: Int? required init(framer: NWProtocolFramer.Instance) {} static let definition = NWProtocolFramer.Definition(implementation: CoolProtocol.self) func start(framer: NWProtocolFramer.Instance) -> NWProtocolFramer.StartResult { return .willMarkReady } func wakeup(framer: NWProtocolFramer.Instance) { } func stop(framer: NWProtocolFramer.Instance) -> Bool { return true } func cleanup(framer: NWProtocolFramer.Instance) { } func handleOutput(framer: NWProtocolFramer.Instance, message: NWProtocolFramer.Message, messageLength: Int, isComplete: Bool) { // How to write a "Message" onto the next protocol handler. I don't want to just write plain data. // How to tell the websocket protocol framer that it's a ping/pong/text/binary... } func handleInput(framer: NWProtocolFramer.Instance) -> Int { // How to handle getting the input from websockets in a message format? I don't want to just get "Data" I would like to know if that data is // a ping, pong, text, binary, ... } } If I implementing this protocol at the application layer, here's how I would send websocket messages class Client { ... func send(string: String) async throws { guard let data = string.data(using: .utf8) else { return } let metadata = NWProtocolWebSocket.Metadata(opcode: .text) let context = NWConnection.ContentContext( identifier: "textContext", metadata: [metadata] ) self.connection.send( content: data, contentContext: context, isComplete: true, completion: .contentProcessed({ [weak self] error in ... }) ) } } You see at the application layer I have access to this context object and can access NWProtocolMetadata on the input and output side, but in NWProtocolFramer.Instance I only see final func writeOutput(data: Data) which doesn't seem to include context anywhere. Is this possible? If not how would you recommend I handle this? I know I could re-write the entire Websocket protocol framer, but it feels like I shouldn't have to if framers are supposed to be able to stack.
0
0
88
5d
Unexpected Insertion of U+2004 (Space) When Using UITextView with Pinyin Input on iOS 18
I encountered an issue with UITextView on iOS 18 where, when typing Pinyin, extra Unicode characters such as U+2004 are inserted unexpectedly. This occurs when using a Chinese input method. Steps to Reproduce: 1. Set up a UITextView with a standard delegate implementation. 2. Use a Pinyin input method to type the character “ㄨ”. 3. Observe that after the character “ㄨ” is typed, extra spaces (U+2004) are inserted automatically between the characters. Code Example: class ViewController: UIViewController { @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } } extension ViewController: UITextViewDelegate { func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { print("shouldChangeTextIn: range \(range)") print("shouldChangeTextIn: replacementText \(text)") return true } func textViewDidChange(_ textView: UITextView) { let currentText = textView.text ?? "" let unicodeValues = currentText.unicodeScalars.map { String(format: "U+%04X", $0.value) }.joined(separator: " ") print("textViewDidChange: textView.text: \(currentText)") print("textViewDidChange: Unicode Scalars: \(unicodeValues)") } } Output: shouldChangeTextIn: range {0, 0} shouldChangeTextIn: replacementText ㄨ textViewDidChange: textView.text: ㄨ textViewDidChange: Unicode Scalars: U+3128 ------------------------ shouldChangeTextIn: range {1, 0} shouldChangeTextIn: replacementText ㄨ textViewDidChange: textView.text: ㄨ ㄨ textViewDidChange: Unicode Scalars: U+3128 U+2004 U+3128 ------------------------ shouldChangeTextIn: range {3, 0} shouldChangeTextIn: replacementText ㄨ textViewDidChange: textView.text: ㄨ ㄨ ㄨ textViewDidChange: Unicode Scalars: U+3128 U+2004 U+3128 U+2004 U+3128 This issue may affect text processing, especially in cases where precise text manipulation is required, such as calculating ranges in shouldChangeTextIn.
2
0
180
2d
Logic Pro loads AUv3 when compiled in Swift 5 but not Swift 6
I have spent a long time refactoring lots of older Swift code to compile without error in Swift 6. The app is a v3 audio unit host and audio unit. Having installed Sonoma and XCode 16 I compile the code using Swift 6 and it compiles and runs without any warnings or errors. My host will load my AU no problem. LOGIC PRO is still the ONLY audio unit host that will load native Mac V3 audio units and so I like to test my code using Logic. In Sonoma with XCode 16... My AU passes the most stringent AUVAL tests both in terminal and Logic pro. If I compile the AU source in Swift 5 Logic will see the AU, load it and run it without problems. But when I compile the AU in Swift 6 Logic sees the AU, will scan it and verify it passes the tests but will not load the AU. In XCode I see a log message that a "helper application failed to run" but the debugger never connects to the AU and I don't think Logic even gets as far as instantiating the AU. So... what is causing this? I'm stumped.. Developing AUv3 is a brain-aching maze of undocumented hurdles and I'm hoping someone might have found a solution for this one. Meanwhile I guess my only option is to continue using the Swift 5 compiler. (appending a little note just to mention that all the DSP code is written in C/C++, Swift is used mainly for the user interface and also does some offline thready work )
1
0
116
6d
Issue Sending Multicast Packets Across Multiple Interfaces Using NWConnectionGroup
Hi everyone, I'm currently working on a project where I need to send multicast packets across all available network interfaces using Apple Network Framework's NWConnectionGroup. Specifically, the MacBook (device I am using for sending multicast requests, MacOS: 15.1) is connected to two networks: Wi-Fi (Network 1) and Ethernet (Network 2), and I need to send multicast requests over both interfaces. I tried using the .requiredInterface property as suggested by Eskimo in this post, but I’m running into issues. It seems like I can't create an NWInterface object because it doesn't have any initializers. Here is the code which I wrote: var multicast_group_descriptor : NWMulticastGroup var multicast_endpoint : NWEndpoint multicast_endpoint = NWEndpoint.hostPort(host: NWEndpoint.Host("234.0.0.1"), port: NWEndpoint.Port(rawValue: 49154)!) var connection_group : NWConnectionGroup var multicast_params : NWParameters multicast_params = NWParameters.udp var interface = NWInterface(NWInterface.InterfaceType.wiredEthernet) I get following error: 'NWInterface' cannot be constructed because it has no accessible initializers I also experimented with the .requiredInterfaceType property. Even when I set it to .wiredEthernet and then change it to .wifi, I am still unable to send requests over the Wi-Fi network. Here is the code I wrote: var multicast_params : NWParameters multicast_params = NWParameters.udp multicast_params.allowLocalEndpointReuse = true multicast_params.requiredInterfaceType = .wiredEthernet var ip = multicast_params.defaultProtocolStack.internetProtocol! as! NWProtocolIP.Options ip.disableMulticastLoopback = true connection_group = NWConnectionGroup(with: multicast_group_descriptor, using: multicast_params) connection_group.stateUpdateHandler = { state in print(state) if state == .ready { connection_group.send(content: "Hello from machine on 15".data(using: .utf8)) { error in print("Send to mg1 completed on wired Ethernet with error \(error?.errorCode)") var params = connection_group.parameters params.requiredInterfaceType = .wifi connection_group.send(content: "Hello from machine on 15 P2 on Wi-Fi".data(using: .utf8)) { error in print("Send to mg1 completed on Wi-Fi with error \(error?.errorCode)") } } } } Is this expected behavior when using NWConnectionGroup? Or is there a different approach I should take to ensure multicast requests are sent over both interfaces simultaneously? Any insights or suggestions would be greatly appreciated! Thanks in advance, Harshal
2
0
150
6d
Rectangle change size by swipe
Hi,, How can I make a rectangle become taller as I swipe down on my trackpad?" struct BlueRectangleView: View { var body: some View { VStack { Rectangle() .fill(Color.blue) .frame(width: 200, height: 100) .cornerRadius(10) .shadow(radius: 5) .padding() } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(Color.white) } } struct BlueRectangleView_Previews: PreviewProvider { static var previews: some View { BlueRectangleView() } }
2
0
139
6d
Failed to generate JWT token error WeatherKit
Hi, I'm trying to implement WeatherKit for the first time and I am seeing this error when calling for the weather: Failed to generate jwt token for: com.apple.weatherkit.authservice with error: Error Domain=WeatherDaemon.WDSJWTAuthenticatorServiceListener.Errors Code=2 "(null)" and Encountered an error when fetching weather data subset; location=<+51.57750785,-2.08241362> +/- 6.55m (speed -1.00 mps / course -1.00) @ 11/01/2025, 11:50:45 Greenwich Mean Time, error=WeatherDaemon.WDSJWTAuthenticatorServiceListener.Errors 2 Error Domain=WeatherDaemon.WDSJWTAuthenticatorServiceListener.Errors Code=2 "(null)" I have: Enabled the WeatherKit capability in my iOS app in XCode Added Weatherkit to the AppID in the developer portal Any suggestions what else I can check? I'm running iOS 18.2.1 on 15 ProMax with XCode 16.2
5
0
186
6d
https://forums.developer.apple.com/forums/post/question
Hi everyone, I’m working on an iOS app using both UITableViewDiffableDataSource and SwiftUI, and I’m facing two separate but puzzling issues: UITableViewDiffableDataSource Not Reusing Cells on first applying after initial Snapshot. After applying first time it is working as expected from second time. SwiftUI View’s inside UITableViewCell onDisappear Not Triggering the on first changes of snapshot after initial snapshot. With normal UITableView it is working fine. Issue causing - it is causing player &amp; cells to retain memory extensively Sample gist code for reproducing with diffable (DiffableTableViewExampleViewController) and working fine without diffable (RegularTableViewExampleViewController) https://gist.github.com/SURYAKANTSHARMA/d83fa9e7e0de309e27485100ba5aed17 Any insights or suggestions for these issues would be greatly appreciated! Thanks in advance!
0
0
113
1w