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

App hangs while opening from background
Hi, My app hangs for about a second when I open the app when it's been in background phase. It doesn't hang every time, but it hangs randomly (like once in 10 times) when I open the app again. I am not able to reproduce what causes this hang. Hang Detection provides hang logs (spindump) when hang occurs. It has something to do with MusicKit as logs mention it but I cannot understand what it is. Please help me understand these logs. I am running iOS 17 beta 1 with MusicKit and ApplicationMusicPlayer. Heaviest stack for the main thread of the target process: 69 start + 2104 (dyld + 87288) [0x1b719b4f8] 69 ??? (Timed + 32864) [0x104ae8060] 69 ??? (SwiftUI + 980040) [0x19840a448] 69 ??? (SwiftUI + 1071088) [0x1984207f0] 69 ??? (SwiftUI + 1667804) [0x1984b22dc] 69 UIApplicationMain + 340 (UIKitCore + 3740336) [0x196c602b0] 69 -[UIApplication _run] + 888 (UIKitCore + 3741260) [0x196c6064c] 69 GSEventRunModal + 164 (GraphicsServices + 4644) [0x1d6199224] 69 CFRunLoopRunSpecific + 600 (CoreFoundation + 527792) [0x1947fedb0] 68 __CFRunLoopRun + 1996 (CoreFoundation + 509348) [0x1947fa5a4] 68 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 (CoreFoundation + 626340) [0x194816ea4] 68 _dispatch_main_queue_callback_4CF + 44 (libdispatch.dylib + 75296) [0x19c404620] 67 _dispatch_main_queue_drain + 744 (libdispatch.dylib + 76056) [0x19c404918] 67 swift_job_runImpl(swift::Job*, swift::ExecutorRef) + 72 (libswift_Concurrency.dylib + 274348) [0x19f58cfac] 67 swift::runJobInEstablishedExecutorContext(swift::Job*) + 416 (libswift_Concurrency.dylib + 269688) [0x19f58bd78] 66 ??? (MusicKit + 4857464) [0x208aabe78] 66 ??? (MusicKit + 4856108) [0x208aab92c] 66 -[MusicKit_SoftLinking_MPMusicPlayerController nowPlayingItem] + 24 (MusicKit + 157364) [0x2086306b4] 66 -[MPMusicPlayerController nowPlayingItem] + 24 (MediaPlayer + 1358540) [0x1a681bacc] 66 -[MPMusicPlayerController _nowPlaying] + 372 (MediaPlayer + 1329552) [0x1a6814990] 66 -[MPMusicPlayerController onServer:] + 52 (MediaPlayer + 1333428) [0x1a68158b4] 63 -[MPMusicPlayerApplicationController _establishConnectionIfNeeded] + 1768 (MediaPlayer + 1553848) [0x1a684b5b8] 63 _NSXPCDistantObjectSimpleMessageSend1 + 60 (Foundation + 208348) [0x1937daddc] 63 -[NSXPCConnection _sendSelector:withProxy:arg1:] + 116 (Foundation + 208548) [0x1937daea4] 62 -[NSXPCConnection _sendInvocation:orArguments:count:methodSignature:selector:withProxy:] + 2160 (Foundation + 214664) [0x1937dc688] 62 __NSXPCCONNECTION_IS_WAITING_FOR_A_SYNCHRONOUS_REPLY__ + 16 (Foundation + 652944) [0x193847690] 62 xpc_connection_send_message_with_reply_sync + 264 (libxpc.dylib + 67488) [0x1fc00d7a0] 62 dispatch_mach_send_with_result_and_wait_for_reply + 60 (libdispatch.dylib + 127760) [0x19c411310] 62 _dispatch_mach_send_and_wait_for_reply + 540 (libdispatch.dylib + 126832) [0x19c410f70] 62 mach_msg + 24 (libsystem_kernel.dylib + 4692) [0x1da082254] 62 mach_msg_overwrite + 436 (libsystem_kernel.dylib + 83544) [0x1da095658] 62 mach_msg2_trap + 8 (libsystem_kernel.dylib + 3332) [0x1da081d04] *62 ??? (<31E57057-A9A0-3BE5-90CB-5C08E9683B34> + 217132) [0xfffffff007e0102c] Thank you. CC @JoeKun
2
0
1k
Oct ’23
XCode 14.3.x and XCode 15 Beta Hangs On Compiling
We have a 7-year old codebase that uses a mix of frameworks including Rx and Firebase through Cocoapods. The compilation works fine up to XCode 14.2 but for some unknown reason the compilation just stuck / hang on XCode 14.3.x and XCode 15. There are several warnings in the codebase but the compiler does not output any error. Which is why we don't know what the exact issue(s) is/are. What's the change in XCode 14.3.x that could be causing this issue? If anyone has an idea on possible fix, willing to try it out.
2
0
1.3k
Oct ’23
Conversion from Base64 Public Key Data to SecKey and convert back from SecKey to Public Key Data are not the same. How can i resolve this?
I am trying to convert publicKeyFromDongleData to SecKey, then perform some tasks. After that, I want to convert SecKey to b64 String. I am assuming that publicKeyFromDongleData and b64 string will be the same. But, surprisingly, they are not the same. How can i resolve the issue? Is there any way around? My goal is to retain the public key before and after converting the same. let publicKeyFromDongleData = Data.init(base64Encoded: publicKeyFromDongle) guard let publicKeySecKey = SecKeyCreateWithData(publicKeyFromDongleData! as CFData, keyDict as CFDictionary, &amp;error) else { print("Failed to create public key:", error!.takeRetainedValue()) return nil } //var error:Unmanaged&lt;CFError&gt;? if let cfdata = SecKeyCopyExternalRepresentation(publicKeySecKey, &amp;error) { let data:Data = cfdata as Data let b64Key = data.base64EncodedString() print("after : \n") print(b64Key) }
3
0
923
Oct ’23
Which is already presenting occurs when another View is presented while the Menu is displayed in SwiftUI.
Certainly, here's an explanation and the minimal code to reproduce the issue in English: In SwiftUI, attempting to present a sheet or any other presentation view while a Menu view is open causes a conflict. This is because SwiftUI does not allow multiple presentation views to be open at the same time. Here's the simplest code to reproduce the issue: import SwiftUI struct ContentView: View { @State var showSheet = false var body: some View { VStack { Menu { Button("Option 1") { } Button("Option 2") { } } label: { Text("Open Menu") } Button(action: { showSheet = true }) { Text("Open Sheet") } .sheet(isPresented: $showSheet) { Text("Hello, Sheet!") } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
2
1
1k
Feb ’24
EXC_BAD_ACCESS when initializing a Model class with a custom class property
I have multiple classes that are contained within one another. Initializing class A(no other classes as properties) has no issues, but the moment that it tries to initialize class B, which takes class A as a property, an EXC_BAD_ACCESS error is thrown while attempting to set the first property value. Class A: import Foundation import SwiftData @Model public class Service: Identifiable, Equatable, Codable { @Attribute(.unique) public var id: UUID public var title: String public var price: Int public var stripePriceId: String public var servicePhoto: String public var serviceLength: Int public var category: [String] init(id: UUID, title: String, price: Int, stripePriceId: String, servicePhoto: String, serviceLength: Int, category: Array<String>) { self.id = id self.title = title self.price = price self.stripePriceId = stripePriceId self.servicePhoto = servicePhoto self.serviceLength = serviceLength self.category = category } } Class B: import Foundation import SwiftData import SwiftUI @Model public class ServiceOrder: Identifiable, Codable, Equatable { public var id: UUID @Relationship(.noAction) public var service: Service public var quantity: Int = 1 public var subtotal: Int { return service.price * quantity } public init(id: UUID = UUID(), service: Service, quantity: Int) { self.id = id self.service = service self.quantity = quantity } public func getValue<T>(for key: KeyPath<ServiceOrder, T>) -> T { return self[keyPath: key] } // This is where the error is being thrown. The custom setValue and getValue methods were added to every class to mitigate an 'Ambiguous use of __Value()' error, but that's for another thread public func setValue<T>(for key: ReferenceWritableKeyPath<ServiceOrder, T>, to newValue: T) { self[keyPath: key] = newValue } // This was added to see if following the Builder pattern might mitigate the issue by ensuring that all properties were initialized before being passed in, it did not change anything class ServiceOrderBuilder { private var id: UUID? private var service: Service? private var quantity: Int? init() { } init(id: UUID = UUID(), service: Service, quantity: Int = 1) { self.id = id self.service = service self.quantity = quantity } func setId(id: UUID = UUID()) -> ServiceOrderBuilder { self.id = id return self } func setService(service: Service) -> ServiceOrderBuilder { self.service = service return self } func setQuantity(quantity: Int = 1) -> ServiceOrderBuilder { self.quantity = quantity return self } func build() -> ServiceOrder? { guard let id = id, let service = service, let quantity = quantity else { return nil } return ServiceOrder(id: id, service: service, quantity: quantity) } } Here's where I'm doing the initialization of everything. I'm trying to just create sample data. import SwiftData import Foundation @MainActor public let previewContainer: ModelContainer = { do { var container = try ModelContainer( for: [Event.self, Braider.self, Queue.self, QueueSlot.self, Cart.self, ServiceOrder.self], ModelConfiguration(inMemory: true) ) var context = container.mainContext var serviceSampleData: [Service] = [ Service( id: UUID(), title: "Event Braid", price: 20, stripePriceId: "", servicePhoto: "", serviceLength: 15, category: []), ..., ] serviceSampleData.forEach { service in context.insert(service) } // This is where the error is thrown, no issue initializing the above Services var serviceOrder1: ServiceOrder = ServiceOrder( service: serviceSampleData[0], quantity: 1) context.insert(serviceOrder1) // ...continue building higher classes/Models that utilize the lower ones return container } catch { print("Failed to create container") do { return try ModelContainer( for: [Event.self], ModelConfiguration(inMemory: true) ) } catch { fatalError() }} }() I assumed that this was a SwiftData issue, as I mentioned in response to this post but looking back this issue has been happening for 7+ years, so now I'm assuming I'm doing something incorrect.
1
0
968
Aug ’23
macOS get SSID changes?
I've had a little personal utility running for several versions of macOS that uses let client = CWWiFiClient.shared() if let ssid_name = client.interface()?.ssid() to get the current SSID name and prints it (along with a bunch of other active network details. With the most recent Sonoma Beta 2 and Xcode beta 2, this always returns nil. Doing the same thing in a playground works as expected. Is this a purposeful change or a bug I should file?
29
2
5.2k
Mar ’24
Unable to Verify App: An internet connection is required to verify the trust of the developer' ... This app will not be available until verified.
We are working on a new iOS application utilizing the new iOS 17 APIs, and I have updated Xcode to Xcode 15 Beta, and my iPhone 12 Pro to iOS 17 Beta 2, though this issue was also present on iOS 17 Beta 1. In Xcode, for "Signing and Capabilities" I have my Team set to my personal team, utilizing the "Automatically manage signing" tick. While the app will build and install on my phone, I immediately receive this error, with no popup to trust the developer. Going to Settings > General > VPN and Device Management, I can see my Development Team, and I am able to Trust my team. When trying to then Verify App(s), it tells me it will use my internet connection to verify the application. However, it will then do nothing, with no error, regardless of how many times I attempt to verify. Trying to open the app from my home screen will result in the repeated "Unable to Verify Error". Trying to reset network settings does not result in any change in this behavior, nor does a reset of the phone. I have tried 4 different high quality WiFi networks, as well as a fully connection AT&T cellular LTE connection, and still receive this error. I am running out of diagnostic scenarios, and I'm curious if anyone has found a resolution to this?
37
11
30k
Apr ’24
iPadOS: [API] Failed to create 0x88 image slot (alpha=1 wide=0) (client=0xfbe80e61) [0x5 (os/kern) failure]
I got the error "[API] Failed to create 0x88 image slot (alpha=1 wide=0) (client=0xfbe80e61) [0x5 (os/kern) failure]" when using NavigationStack of SwiftUI for navigation. It only happen in iPadOS (16.4) but not iOS in iPhone. Below is the view I am using. struct NewView: View { var body: some View { NavigationStack { VStack { NavigationLink("Show Detail View") { DetailView() } } .navigationTitle("Navigation") } } } struct DetailView: View { var body: some View { Text("This is the detail view") } } Anyone know the reason?
3
1
2.2k
Oct ’23
SwiftData error 134020 - "The model configuration used to open the store is incompatible with the one that was used to create the store."
Hi all, I have tried everything (that i'm aware of) but i cannot seem to get around this error. My app is setup using only SwiftData and is basically a custom version of the apps shown in SwiftData docs. I have done the following to try to debug: Deleted app from device Clean and re-build Delete derived data and rebuild I have tried reverting changes made to the @Models i have define Every combination of the above steps + rebuilding Im at a loss. No clue how to resolve this. Some weird observations. This error only occurs after the first context.insert call. The first is successful and data is properly persisted across app launches. All subsequent attempts to insert result in the following error: Error Domain=NSCocoaErrorDomain Code=134020 "The model configuration used to open the store is incompatible with the one that was used to create the store." UserInfo={NSAffectedObjectsErrorKey=<NSManagedObject: 0x2824004b0> (entity: Track; id: 0x2807a7de0 <x-coredata:///Track/tB9B77486-8F60-4F63-848D-D1C5CC67BA526>; data: { createdAt = "2023-07-02 23:45:45 +0000"; name = Test; })}
5
3
1.6k
Sep ’23
XCUIElement's Print Statement Not Including Nested Button
Example Image: Expected Behavior: When an XCUIElement is rendered from a screen with (Initial Conditions): An ImageView with.. isUserInteractionEnabled = YES… IsAccessibilityElement = YES… A nested button… isUserInteractionEnabled = YES… IsAccessibilityElement = YES… Assigned to the ImageViews accessibility elements array XCUIElement’s print statement includes the nested button Current Behavior: When an XCUIElement is rendered from a screen with: (above Initial Conditions) XCUIElement’s print statement only include the ImageView Attempted Fixes: Combinations of the Initial Conditions: Attempted all combinations of Initial Condition variable values. (ie: myImageView.accessibilityElements = [imageView, nestedButton] myImageView.accessibilityElements = [nestedButton] isUserInteractionEnabled = YES/NO [for both] IsAccessibilityElement = YES/NO [for both] etc…) Debug Print: Image View with No Descendants - Image, 0x7fa875d23e80, {{172.7, 292.7}, {45.0, 41.7}}, label: 'demo image' po element.images and po element.buttons - Find: Descendants matching type Image Output: { Image, 0x7fa876e14e70, {{-8.0, 99.0}, {136.7, 109.3}} Image, 0x7fa876e14f80, {{-8.0, 741.7}, {136.7, 102.3}} Image, 0x7fa876e13da0, {{269.7, 737.0}, {136.3, 123.0}} Image, 0x7fa876e1a060, {{172.7, 292.7}, {45.0, 41.7}}, label: 'demo image' } Output: { Button, 0x7fa875c12740, {{0.0, 47.0}, {68.0, 44.0}}, label: 'myApp UIKit' Button, 0x7fa875c24f00, {{338.0, 47.0}, {44.0, 44.0}}, identifier: 'Settings Button', label: 'Settings' Button, 0x7fa875c2c800, {{175.0, 533.0}, {40.0, 40.0}} Button, 0x7fa875c2cf30, {{183.0, 541.0}, {24.0, 24.0}} Button, 0x7fa875c2fa20, {{40.0, 659.3}, {153.0, 44.0}}, label: 'Left' Button, 0x7fa875c30cd0, {{197.0, 659.3}, {153.0, 44.0}}, label: 'Right' } Comparing the coordinates of the parent image view and the nested button, the button isn't here. The 24x24 button that appears comes from another view on the same screen, noting the ample y coordinate from the parent image view. Request: Request that Apple, in the spirit of XCUI framework being to be near to human experience include this common design case
1
1
588
Aug ’23
[WindowHosting] UIScene property of UINSSceneViewController was accessed before it was set. What does this mean?
Getting this error several times when presenting a modal window over my splitview window when running it on my Mac using Swift/Mac Catalyst in XCode 14.2. When I click the Cancel button in the window then I get Scene destruction request failed with error: (null) right after an unwind segue. 2023-07-04 16:50:45.488538-0500 Recipes[27836:1295134] [WindowHosting] UIScene property of UINSSceneViewController was accessed before it was set. 2023-07-04 16:50:45.488972-0500 Recipes[27836:1295134] [WindowHosting] UIScene property of UINSSceneViewController was accessed before it was set. 2023-07-04 16:50:45.496702-0500 Recipes[27836:1295134] [WindowHosting] UIScene property of UINSSceneViewController was accessed before it was set. 2023-07-04 16:50:45.496800-0500 Recipes[27836:1295134] [WindowHosting] UIScene property of UINSSceneViewController was accessed before it was set. 2023-07-04 16:50:45.994147-0500 Recipes[27836:1295134] Unbalanced calls to begin/end appearance transitions for <UINavigationController: 0x7f7fdf068a00>. bleep 2023-07-04 16:51:00.655233-0500 Recipes[27836:1297298] Scene destruction request failed with error: (null) I don't quite understand what all all this means. (The "bleep" was a debugging print code I put in the unwind segue). I'm working through Apple's Mac Catalyst tutorial but it seems to be riddled with bugs and coding issues, even in the final part of the completed app which I dowmloaded and ran. I don't see these problems on IPad simulator. I don't know if it's because Catalyst has problems itself or there's something else going on that I can fix myself. Any insight into these errors would be very much appreciated! PS: The app seems to run ok on Mac without crashing despite the muliple issues
3
2
1.1k
Oct ’23
open a New View from a item in a contextual menu
Bonjour as the title says: I have a contextual menu in my app, using swift, I want to open a New View from a item in a contextual menu when I click on the like to go to MainView, nothings happens Please Help me I am very new in IOS programmation here is my code so far: .toolbar { ToolbarItem(placement: .navigationBarTrailing) { Menu { NavigationLink(destination:MainView()){ Label("MainView", systemImage: "house") } Button(action: { // Show modal text for copyright }) { Label("Modal Text", systemImage: "text.book.closed") } Button(action: { // Go to HelpView }) { Label("HelpView", systemImage: "questionmark.circle") } } label: { Image(systemName: "house") } } } Thanks for helping me I have been fighting with this for hours David
8
0
645
Aug ’23
Xcode 15b3 Swift 5.9 C++ Interop with Network Extension
Just a quick observation. I find that the NSNotification.Name NEVPNStatusDidChange is not visible when the Swift Compiler setting: C++ and Objective-C Interoperability is set to C++/Objective-C++. Simply switching between C/Objective-C and C++/Objective-C++, a successfully building app is no longer able to build with error: Type 'NSNotification.Name?' has no member 'NEVPNStatusDidChange'. The Swift code being used is: NotificationCenter.default.addObserver(self, selector: #selector(self.updateNetworkStatus(_:)), name: .NEVPNStatusDidChange, object: nil)
4
0
832
Sep ’23
Querying HealthKit for Manually-Entered Medication
I'm trying to query HealthKit for all of users medications, including prescribed medications and user-entered medications. Using a HKSampleQuery with type HKClinicalTypeIdentifierMedicationRecord, I'm able to fetch medications that have been prescribed by a healthcare provider (eg medications associated with clinical FHIR records): let type = HKClinicalType(.medicationRecord) let predicate = HKQuery.predicateForClinicalRecords(withFHIRResourceType: .medicationStatement) let query = HKSampleQuery(sampleType: type, predicate: predicate, limit: kRecordLimit, sortDescriptors: nil) { q, samples, error in // this returns only -clinical- records // it doesnt include manually entered meds } However, medications which I have manually entered into the Health app with a user-defined schedule and dosing do NOT appear in the results of this query. is it possible to fetch medications which have been manually entered by the user?
3
1
1k
Oct ’23
On/Off Button Title in updateUI()
I am working through the Getting Started with App Development and on Page 142 it has you write in the updateUI() function if else statement lightButton.setTitle("Off", for: .normal) and lightButton.setTitle("On", for: .normal). My app crashes every time after building it and running it. Image reference below. The app works perfectly fine before adding these two statements. import UIKit class ViewController: UIViewController { @IBOutlet var lightButton: UIButton! var lightOn = true fileprivate func updateUI() { if lightOn { view.backgroundColor = .white lightButton.setTitle("Off", for: .normal) } else { view.backgroundColor = .black lightButton.setTitle("On", for: .normal) } } @IBAction func buttonPressed(_ sender: Any) { lightOn.toggle() updateUI() } override func viewDidLoad() { super.viewDidLoad() updateUI() // Do any additional setup after loading the view. } } Getting this error at the end. libc++abi: terminating due to uncaught exception of type NSException (lldb)
5
0
408
Oct ’23
My loop makes a click noise each time it starts
The loop plays smoothly in audacity but when I run it in the device or simulator it clicks each loop at different intensities. I config the session at App level: let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setCategory(.playback, mode: .default, options: [.mixWithOthers]) try audioSession.setActive(true) } catch { print("Setting category session for AVAudioSession Failed") } And then I made my method on my class: func playSound(soundId: Int) { let sound = ModelData.shared.sounds[soundId] if let bundle = Bundle.main.path(forResource: sound.filename, ofType: "flac") { let backgroundMusic = NSURL(fileURLWithPath: bundle) do { audioPlayer = try AVAudioPlayer(contentsOf:backgroundMusic as URL) audioPlayer?.prepareToPlay() audioPlayer?.numberOfLoops = -1 // for infinite times audioPlayer?.play() isPlayingSounds = true } catch { print(error) } } } Does anyone have any clue? Thanks! PS: If I use AVQueuePlayer and repeat the item the click noise disappear (but its no use, because I would need to repeat it indefinitely without wasting memory), if I use AVLooper I get a silence between loops. All with the same sound. Idk :/ PS2: The same happens with ALAC files.
4
2
808
2w