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

Intermittent failure to connect to a hidden AP when connecting programmatically
Hello there! We have an app that connects to an external device via Wi-Fi to send and query content from it. This external device generates a hidden AP that the phone connects against. However, sometimes the app fails to connect to the external device with the system alert "Unable to join the network...". We have been debugging for a couple but couldn't find any clear reason of why this thing is happening. What could be the reason behind this alert appearing? For the connection, we are using the NEHotspotConfigurationManager to connect to the AP of this external device. The configuration for the connection is the following: NEHotspotConfiguration( ssid: ssid, passphrase: password, isWEP: false ) configuration.hidden = true There are some logs that we extracted that show two connections. One happened at 20:37, which was a successful connection. wifi_logs_success 2.log Another connection was made at 20:38, which failed. wifi_logs_failure.log Inspecting the logs, one difference that I see between them is the __WiFiDeviceManagerDispatchUserForcedAssociationCallback: result %lld, which in the successful case is 0 and in the failed case is 1. Can anyone help with this? We're very lost on why this configuration could be an issue at all.
2
0
179
2w
CreateML/CoreML Issues with Large Dataset
Hello All, I'm developing a machine learning model for image classification, which requires managing an exceptionally large dataset comprising over 18,000 classes. I've encountered several hurdles while using Create ML, and I would appreciate any insights or advice from those who have faced similar challenges. Current Issues: Create ML Failures with Large Datasets: When using Create ML, the process often fails with errors such as "Failed to create CVPixelBufferPool." This issue appears when handling particularly large volumes of data. Custom Implementation Struggles: To bypass some of the limitations of Create ML, I've developed a custom solution leveraging the MLImageClassifier within the CreateML framework in my own SwiftUI MacOS app. Initially I had similar errors as I did in Create ML, but I discovered I could move beyond the "extracting features" stage without crashing by employing a workaround: using a timer to cancel and restart the job every 30 seconds. This method is the only way I've been able to finish the extraction phase, even with large datasets, but it causes many errors in the console if I allow it to run too long. Lack of Progress Reporting: Using MLJob<MLImageClassifier>, I've noticed that progress reporting stalls after the feature extraction phase. Although system resources indicate activity, there is no programmatic feedback on what is occurring. Things I've Tried: Data Validation: Ensured that all images in the dataset are valid and non-corrupted, which helps prevent unnecessary issues from faulty data. Custom Implementation with CreateML Framework: Developed a custom solution using the MLImageClassifier within the CreateML framework to gain more control over the training process. Timer-Based Workaround: Employed a workaround using a timer to cancel and restart the job every 30 seconds to move past the "extracting features" phase, allowing progress even with larger datasets. Monitoring System Resources: Observed ongoing system resource usage when process feedback stalled, confirming background processing activity despite the lack of progress reporting. Subset Testing: Successfully created and tested a model on a subset of the data, which validated the approach worked for smaller datasets and could produce a functioning model. Router Model Concept: Considered training multiple models for different subsets of data and implementing a "router" model to decide which specialized model to utilize based on input characteristics. What I Need Help With: Handling Large Datasets: I'm seeking strategies or best practices for effectively utilizing Create ML with large datasets. Any guidance on memory management or alternative methodologies would be immensely helpful. Improving Progress Reporting: I'm looking for ways to obtain more consistent and programmatic progress updates during the training and testing phases. I'm working on a Mac M1 Pro w/ 32GB RAM, with Apple Silicon and am fully integrated within the Apple ecosystem. I am very grateful for any advice or experiences you could share to help overcome these challenges. Thank you! I've pasted the relevant code below: func go() { if self.trainingSession == nil { self.trainingSession = createTrainingSession() } if self.startTime == nil { self.startTime = Date() } job = try! MLImageClassifier.resume(self.trainingSession) job.phase .receive(on: RunLoop.main) .sink { phase in self.phase = phase } .store(in: &cancellables) job.checkpoints .receive(on: RunLoop.main) .sink { checkpoint in self.state = "\(checkpoint)\n\(self.job.progress)" self.progress = self.job.progress.fractionCompleted + 0.2 self.updateTimeEstimates() } .store(in: &cancellables) job.result .receive(on: DispatchQueue.main) .sink(receiveCompletion: { completion in switch completion { case .failure(let error): print("Training Failed: \(error.localizedDescription)") case .finished: print("πŸŽ‰πŸŽ‰πŸŽ‰πŸŽ‰ TRAINING SESSION FINISHED!!!!") self.trainingFinished = true } }, receiveValue: { classifier in Task { await self.saveModel(classifier) } }) .store(in: &cancellables) } private func createTrainingSession() -> MLTrainingSession<MLImageClassifier> { do { print("Initializing training Data...") let trainingData: MLImageClassifier.DataSource = .labeledDirectories(at: trainingDataURL) let modelParameters = MLImageClassifier.ModelParameters( validation: .split(strategy: .automatic), augmentation: self.augmentations, algorithm: .transferLearning( featureExtractor: .scenePrint(revision: 2), classifier: .logisticRegressor ) ) let sessionParameters = MLTrainingSessionParameters( sessionDirectory: self.sessionDirectoryURL, reportInterval: 1, checkpointInterval: 100, iterations: self.numberOfIterations ) print("Initializing training session...") let trainingSession: MLTrainingSession<MLImageClassifier> if FileManager.default.fileExists(atPath: self.sessionDirectoryURL.path) && isSessionCreated(atPath: self.sessionDirectoryURL.path()) { do { trainingSession = try MLImageClassifier.restoreTrainingSession(sessionParameters: sessionParameters) } catch { print("error resuming, exiting.... \(error.localizedDescription)") fatalError() } } else { trainingSession = try MLImageClassifier.makeTrainingSession( trainingData: trainingData, parameters: modelParameters, sessionParameters: sessionParameters ) } return trainingSession } catch { print("Failed to initialize training session: \(error.localizedDescription)") fatalError() } }
0
0
208
2w
Swift Exception Handling in Apple OSes
I have an app whose logic is in C++ and rest of the parts (UI) are in Swift and SwiftUI. Exceptions can occur in C++ and Swift. I've got the C++ part covered by using the Linux's signal handler mechanism to trap signals which get raised due to exceptions. But how should I capture exceptions in Swift? When I say exceptions in Swift, I mean, divide by zero, force unwrapping of an optional containing nil, out of index access in an array, etc. Basically, anything that can go wrong, I don't want my app to abruptly crash... I need a chance to finalise my stuff, alert the user, prepare diagnostic reports and terminate. I'm looking for a 'catch-all' exception handler. As an example, let's take Android. In Android, there is the setDefaultUncaughtExceptionHandler method to register for all kinds of exceptions in any thread in Kotlin. I'm looking for something similar in Swift that should work for macOS, iOS &amp; iPadOS, tvOS and watchOS. I first came across the NSSetUncaughtExceptionHandler method. My understanding is, this only works when I explicitly raise NSExceptions. When I tested it, observed that the exception handler didn't get invoked for either case - divide by zero or invoking raise. class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { Log("AppDelegate.applicationDidFinishLaunching(_:)") // Set the 'catch-all' exception handler for Swift exceptions. Log("Registering exception handler using NSSetUncaughtExceptionHandler()...") NSSetUncaughtExceptionHandler { (exception: NSException) in Log("AppDelegate.NSUncaughtExceptionHandler()") Log("Exception: \(exception)") } Log("Registering exception handler using NSSetUncaughtExceptionHandler() succeeded!") // For C++, use the Linux's signal mechanism. ExceptionHandlingCpp.RegisterSignals() //ExceptionHandlingCpp.TestExceptionHandler() AppDelegate.TestExceptionHandlerSwift() } static func TestExceptionHandlerSwift() { Log("AppDelegate.TestExceptionHandlerSwift()") DivisionByZero(0) } private static func DivisionByZero(_ divisor: Int) { Log("AppDelegate.DivisionByZero()") let num1: Int = 2 Log("Raising Exception...") //let result: Int = num1/divisor let exception: NSException = NSException(name: NSExceptionName(rawValue: "arbitrary"), reason: "arbitrary reason", userInfo: nil) exception.raise() Log("Returning from DivisionByZero()") } } In the above code, dividing by zero, nor raising a NSException invokes the closure passed to NSSetUncaughtExceptionHandler, evident from the following output logs AppDelegate.applicationWillFinishLaunching(_:) AppDelegate.applicationDidFinishLaunching(_:) Registering exception handler using NSSetUncaughtExceptionHandler()... Registering exception handler using NSSetUncaughtExceptionHandler() succeeded! ExceptionHandlingCpp::RegisterSignals() .... AppDelegate.TestExceptionHandlerSwift() AppDelegate.DivisionByZero() Raising Exception... Currently, I'm reading about ExceptionHandling framework, but this is valid only for macOS. What is the recommended way to capture runtime issues in Swift?
7
0
309
2w
Camera not detect dataMatrix code
Hello, I have a problem reading a 2D data matrix type code with a camera. In the application, I use AVFoundation to operate the camera and work with 2D codes, and in the vast majority there is no problem with loading. Nothing special. I originally thought it might be a problem in my code, but I got the same result when I tried with the Camera app integrated in IOS. It can be seen that only the LiveText API for text recognition worked. But I am attaching the code with which the camera has a problem, even though the code looks perfectly fine at first glance. A classic handheld 2D code reader will read the code just fine. Can someone please explain to me why the camera, which normally reads these codes at the speed of light, sometimes has a problem with the codes? Thank you [Personal Information Edited by Moderator]
1
0
156
2w
how to show different launch screen for different language
I am making a swift app supporting multi language ,showing proper language ui according user's phone setting language, I want to launch different screen (showing different image, boot-en.jpg, boot-ja.jpg) according language,i created two LaunchScreen files ,LaunchScreen-en.storyboard and LaunchScreen-ja.storyboard and localize them ,and add a different UIImage to them, then create two InfoPlist.strings file with congfiging ."UILaunchStoryboardName" = "LaunchScreen_en"; // "UILaunchStoryboardName" = "LaunchScreen_ja";// and then **config info.plist ** with UILaunchStoryboardName LaunchScreen above all steps ,build and run,hope to see launch screen showing boot-ja.jpg when phone's language is Japanese, showing boot-en.jpg when phone's language is English, but it shows black screen, how to fix this problem, thank you.
1
0
172
2w
Content size of NSWindow returns zero frame after setting view on macOS 15.0 and xCode 16.1
I would like to show a nswindow at a position on screen base on height of the nswindow and its content view. I received zero width and height on macOS 15.0 and xCode 16.1 however they were returned correct width and height on previous macOS version. import Cocoa import SwiftUI class AppDelegate: NSObject, NSApplicationDelegate { private var window: NSWindow! func applicationDidFinishLaunching(_ aNotification: Notification) { window = NSWindow( contentRect: .zero, styleMask: [.miniaturizable, .closable, .resizable], backing: .buffered, defer: false) window.title = "No Storyboard Window" window.contentView = NSHostingView(rootView: ContentView()) // a swiftui view window.center() let windowFrame = window.frame print("window Frame \(windowFrame)") // print width and height zero here window.makeKeyAndOrderFront(nil) } } struct ContentView: View { var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") } .padding() } } I tried window.layoutIfNeeded() after setting contentview but it didn't work How can I get the frame after setting contentview for nswindow on macOS 15.0?
1
0
220
2w
Strange error in com.apple.speech.localspeechrecognition that doesn't affect output?
While running Swift's SpeechRecognition capabilities I get the error below. However, the app successfully transcribes the audio file. So am not sure how worried I have to be, as well, would like to know that if when that error occurred, did that mean that the app went to the internet to transcribe that file? Yes, requiresOnDeviceRecognition is set to false. Would like to know what that error meant, and how much I need to worry about it? Received an error while accessing com.apple.speech.localspeechrecognition service: Error Domain=kAFAssistantErrorDomain Code=1101 "(null)"
0
0
201
2w
How to to expose elements for automation but not for accessibility in swift UIKit?
I have two views in a container view as below @IBOutlet weak var dataDisclosureView: UIStackView! // Main ContainerView @IBOutlet private weak var titleLabel: UILabel! { didSet { titleLabel.text = "Hello" } } @IBOutlet private weak var descriptionLabel: UILabel! { didSet { descriptionLabel.text = "World" } } @IBOutlet weak var descriptionView: UIStackView! { // sub container view containing titleLabel and descriptionLabel didSet { descriptionView.isAccessibilityElement = true descriptionView.accessibilityLabel = "Hello" descriptionView.accessibilityIdentifier = "test_hello" } } @IBOutlet private weak var requestButton: UIButton! { didSet { requestButton.isAccessibilityElement = true requestButton.accessibilityLabel = "Request Button" requestButton.accessibilityIdentifier = "test_button" } } override func viewDidLoad() { super.viewDidLoad() dataDisclosureView.isAccessibilityElement = false dataDisclosureView.accessibilityElements = [ descriptionView ?? "" ] if #available(iOS 17.0, *) { dataDisclosureView.automationElements = [ descriptionView ?? "", requestButton ?? ""] } else { // Fallback on earlier versions } let requestButtonAction = UIAccessibilityCustomAction(name: "start", target: self, selector: #selector( request)) dataDisclosureView.accessibilityCustomActions = [ requestButtonAction ] } Mx issue is I want AccessibilityIdentifers for descriptionLabel,titleLabel,requestButton and hintLabel(For Automation) and accessibility labels for descriptionView and requestButton(VoiceOver Accessibility). But I am unable to see accessibilityIdentifier for Button, TitleLabel and descriptionLabel in AccessibilityInspector. what am I doing wrong here?
1
0
262
3w
How to combine child views and expose containerView for accessibility and at the same time child views for Automation?
I have an image and label inside UIStackView which are inside a viewcontroller. I want to make my UIView accessible. So I wrote below code: var image: UIImage! var myView: UIStackView! var label : UILabel! myView.isAccessibilityElement = true myView.accessibilityLabel = "Hello" myView.accessiblityIdentifier = "test_view" image.accessiblityIdentifier = "test_image" label.accessibilityIdentifier = "test_label" All are UIKit Elements. How to expose mvView to accessibility and only children to automation I tried below two ways, none of them worked: self.view.accessibilityElements = [myView] myView.accessibilityElements = [] from apple documentation : If the object is a view and it’s an accessibility element, and accessibilityElements is empty, the system assigns the list of subviews that have an accessibilityIdentifier to automationElements. myView.automationElements = [myView,image,label] from apple documentation : In some cases, you might want to expose elements for automation but not for accessibility, or vice versa. In a view containing an image with a label under it, for example, you might choose to expose only the label for accessibility. For automation, however, you might include both the image and the label in a test to confirm the both objects exist. In this case, add both the image and the label to automationElements. I am really going crazy with this since many days. Help is very much appreciated.
0
0
199
3w
WidgetKit with SwiftData on macOS
Xcode: 16.1 macOS: Sequoia When I run widget preview, I got the following errors CoreData: error: Store failed to load. <NSPersistentStoreDescription: 0x156237310> (type: SQLite, url: file:///Users/user/Library/Group%20Containers/group.com.app.name/Library/Application%20Support/default.store) with error = Error Domain=NSCocoaErrorDomain Code=256 "The file couldn’t be opened." UserInfo={reason=Unknown failure to access file: 1} with userInfo { reason = "Unknown failure to access file: 1"; } Unresolved error loading container Error Domain=NSCocoaErrorDomain Code=256 "The file couldn’t be opened." UserInfo={reason=Unknown failure to access file: 1} with this code let sharedModelContainer: ModelContainer = { let schema = Schema([Company.self, Person.self]) do { return try ModelContainer(for: schema, configurations: [.init(isStoredInMemoryOnly: false)]) } catch { fatalError("error: \(error)") } }() Does anyone know why this happens and how to fix this?
5
0
198
2w
Widget Intent does not work on macOS Sequoia
Environment Xcode: 16.1 Swift 6 and SwiftUI for macOS development macOS Sequoia I have an app for macOS, and that uses an interactive widget feature. On macOS Sequoia, the widget does not display anything and widget intent doesn't work either. I tested it on macOS Sonoma and it totally works. I assume it's a macOS bug. The app has been working fine before Sequoia. Even on Xcode, when I tried to run the widget preview, Failed to load widget. The operation couldn't be completed. (WidgetKit_Simulator.WidgetDocument.Error error 4.). I could avoid the error by changing version and build numbers, but I still got The operation couldn't be completed. (CHSErrorDomain error 1103.) How am I able to fix the issue? I wanna at least know if its a bug from the app or macOS Sequoia.
0
0
131
3w
Crash casting class from obj_copyClassList to a type
This is similar to this post https://developer.apple.com/forums/thread/700770 on using objc_copyClassList to obtain the available classes. When iterating the list, I try casting the result to an instance of a protocol and that works fine: protocol DynamicCounter { init(controlledByPlayer: Bool, game: Game) } class BaseCounter: NSObject, DynamicCounter { } static func withAllClasses<R>( _ body: (UnsafeBufferPointer<AnyClass>) throws -> R ) rethrows -> R { var count: UInt32 = 0 let classListPtr = objc_copyClassList(&count) defer { free(UnsafeMutableRawPointer(classListPtr)) } let classListBuffer = UnsafeBufferPointer( start: classListPtr, count: Int(count) ) return try body(classListBuffer) } static func initialize() { let monoClasses = withAllClasses { $0.compactMap { $0 as? DynamicCounter.Type } } for cl in monoClasses { cl.initialize() } } The above code works fine if I use DynamicCounter.Type on the cast but crashes if try casting to BaseCounter.Type instead. Is there a way to avoid the weird and non Swift classes?
11
0
362
1w
Search Bar does not work on iOS 18
I belong to an EC shop application developers' team, and we got a crame from a small part of our customers about our application. "Search Bar does not work on iOS 18." This bug doesn't appear on most of our devices updated to iOS 18.0. In some cases, it disappeared by turning [Settings > Accessibility > Touch > Reachability] off. But it is not the same for all customers found the bug. I'm looking for how to fix this bug, and why it happens. I'm not sure but I doubt that this may be a bug of iOS18, UIKit, RxCocoa, RxSwift, or something else. Any information would be welcome. import UIKit import RxSwift import RxCocoa @IBDesignable public final class SearchBar: UISearchBar { var textField: UITextField { if #available(iOS 13.0, *) { return searchTextField } else { return value(forKey: "_searchField") as! UITextField } } private let disposeBag = DisposeBag() private func bind() { textField.rx.isFirstResponder .bind(to: Binder(self) { me, isFirstResponder in // This doesn't work in some iOS 18 devices. me.textField.attributedPlaceholder = placeholderAttributedString(isFirstResponder: isFirstResponder) me.textField.backgroundColor = isFirstResponder ? Asset.Colors.whiteTwo.color : .white if me.useCancelButton { me.showsCancelButton = isFirstResponder } if me.useBookmarkButton { me.showsBookmarkButton = !isFirstResponder } }) .disposed(by: disposeBag) } public override init(frame: CGRect) { super.init(frame: frame) commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override func awakeFromNib() { super.awakeFromNib() commonInit() } public override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() commonInit() } private func commonInit() { bind() } } extension Reactive where Base: SearchBar {} import UIKit import RxSwift import RxCocoa @IBDesignable public final class SearchHeaderView: UIView { @IBOutlet private weak var searchBar: SearchBar! @IBOutlet private weak var cartContainerView: UIView! private let disposeBag = DisposeBag() public override init(frame: CGRect) { super.init(frame: frame) loadFromNib() commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override func awakeFromNib() { super.awakeFromNib() loadFromNib() commonInit() } public override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() loadFromNib() commonInit() } private func commonInit() { bind() } private func bind() { // ↓ This doesn't work in some iOS 18 devices. searchBar.textField.rx.isFirstResponder .bind(to: cartContainerView.rx.isHidden) .disposed(by: disposeBag) } } extension SearchAndCartHeaderView: NibOwnerLoadable {}
0
0
200
3w
ipatool failed
In my Xcode Version 16.0, I try to export an adhoc IPA file (sure the certificate is correct). get error ipatool failed, error in logΒ  2024-10-27 07:56:28 +0000 Output: ruby 2.6.10p210 (2022-04-12 revision 67958) [universal.arm64e-darwin24] /Applications/Xcode.app/Contents/SharedFrameworks/AppThinning.framework/Resources/ipatool:4135: warning: assigned but unused variable - prev /Library/Ruby/Gems/2.6.0/gems/CFPropertyList-3.0.6/lib/cfpropertylist/rbCFPropertyList.rb:83: warning: assigned but unused variable - temp Ignoring date-3.3.4 because its extensions are not built. Try: gem pristine date --version 3.3.4 /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:117:in `require': dlopen(/Library/Ruby/Gems/2.6.0/gems/date-3.3.4/lib/date_core.bundle, 0x0009): tried: '/Library/Ruby/Gems/2.6.0/gems/date-3.3.4/lib/date_core.bundle' (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64e' or 'arm64')), '/System/Volumes/Preboot/Cryptexes/OS/Library/Ruby/Gems/2.6.0/gems/date-3.3.4/lib/date_core.bundle' (no such file), '/Library/Ruby/Gems/2.6.0/gems/date-3.3.4/lib/date_core.bundle' (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64e' or 'arm64')) - /Library/Ruby/Gems/2.6.0/gems/date-3.3.4/lib/date_core.bundle (LoadError) from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:117:in `require' from /Library/Ruby/Gems/2.6.0/gems/date-3.3.4/lib/date.rb:4:in `<top (required)>' from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:117:in `require' from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:117:in `require' from /Library/Ruby/Gems/2.6.0/gems/CFPropertyList-3.0.6/lib/cfpropertylist/rbCFPropertyList.rb:4:in `<top (required)>' from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:65:in `require' from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:65:in `require' from /Library/Ruby/Gems/2.6.0/gems/CFPropertyList-3.0.6/lib/cfpropertylist.rb:3:in `<top (required)>' from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:130:in `require' from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:130:in `rescue in require' from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:34:in `require' from /Applications/Xcode.app/Contents/SharedFrameworks/AppThinning.framework/Resources/ipatool:15:in `<main>' /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load such file -- cfpropertylist (LoadError) from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require' from /Applications/Xcode.app/Contents/SharedFrameworks/AppThinning.framework/Resources/ipatool:15:in `<main>' 2024-10-27 07:56:28 +0000 JSON: error: Error Domain=NSCocoaErrorDomain Code=260 "The file β€œipatool.json” couldn’t be opened because there is no such file." UserInfo={NSUnderlyingError=0x60001d36e790 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}, NSURL=file:///var/folders/dy/b75q3b0500zf9jw82qtzh4xc0000gn/T/IPATool.ytsiVVI/ipatool.json, NSFilePath=/var/folders/dy/b75q3b0500zf9jw82qtzh4xc0000gn/T/IPATool.ytsiVVI/ipatool.json} My Ruby version in mac(in terminal) - ruby -v ruby 3.3.5 (2024-09-03 revision ef084cc8f4) [arm64-darwin24] - which ruby /Users/ayaaboud/.rvm/rubies/ruby-3.3.5/bin/ruby I try to make xcode project lock to my ruby version instead of ruby in system by make executable code but error still exists while export ipa file.
1
2
177
2w
Swift MacOS crash at start when using it on a Mac which is set to french language
A Swift MacOS works with no problem on Intel or ARM Macs (from 11, BigSur to 15, Sequoia) but recently I learned that is crashes when launched on a Mac which language is set to French. I'm not saying this setting is causing the issue, but is the most obvious difference observed compared to many other Macs where the App runs with no problem. The crash occurred in a MacOS intel. See excerpts from crash report below: Process: MySwiftAPP [626] Path: /Volumes/VOLUME/*/MySwiftAPP.app/Contents/MacOS/MySwiftAPP Identifier: Myinfo.MYSwiftAPP Version: X.Y.01 (1) Code Type: X86-64 (Native) Parent Process: launchd [1] User ID: 501 Date/Time: 2021-01-05 01:47:12.0578 +0100 OS Version: macOS 12.2.1 (21D62) Report Version: 12 Bridge OS Version: 3.0 (14Y910) Anonymous UUID: 3579800E-84CC-15C4-2981-320ECF2E1400 Time Awake Since Boot: 62 seconds System Integrity Protection: enabled Crashed Thread: 0 Dispatch queue: com.apple.main-thread Exception Type: EXC_BAD_INSTRUCTION (SIGILL) Exception Codes: 0x0000000000000001, 0x0000000000000000 Exception Note: EXC_CORPSE_NOTIFY Termination Reason: Namespace SIGNAL, Code 4 Illegal instruction: 4 Terminating Process: exc handler [626] Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 MySwiftAPP 0x10c6df5bb 0x10c61d000 + 796091 1 MySwiftAPP 0x10c6be4dc 0x10c61d000 + 660700 2 SwiftUI 0x7ff919a8ff0e closure #1 in AppearanceActionModifier.MergedBox.update() + 72 3 SwiftUI 0x7ff9193d2047 thunk for @escaping @callee_guaranteed () -> () + 12 4 SwiftUI 0x7ff919a91012 partial apply for thunk for @escaping @callee_guaranteed () -> () + 17 5 SwiftUI 0x7ff919bbc028 closure #1 in ViewRendererHost.render(interval:updateDisplayList:) + 2414 6 SwiftUI 0x7ff919ba9fbe ViewRendererHost.render(interval:updateDisplayList:) + 359 7 SwiftUI 0x7ff919c04d56 closure #1 in NSHostingView.layout() + 126 8 SwiftUI 0x7ff919c0dce7 partial apply for thunk for @callee_guaranteed (@guaranteed NSAnimationContext) -> () + 17 9 SwiftUI 0x7ff919c023fd thunk for @escaping @callee_guaranteed (@guaranteed NSAnimationContext) -> () + 36 10 AppKit 0x7ff8113fa152 +[NSAnimationContext runAnimationGroup:] + 55 11 SwiftUI 0x7ff919c04c8a NSHostingView.layout() + 287 12 SwiftUI 0x7ff919c0508a @objc NSHostingView.layout() + 21 13 AppKit 0x7ff811435d7f NSViewLayout + 564 14 AppKit 0x7ff811435851 -[NSView layoutSubtreeWithOldSize:] + 352 15 AppKit 0x7ff811434d68 -[NSView layoutSubtreeIfNeededAndAllowTemporaryEngine:] + 1041 16 AppKit 0x7ff811677f22 +[NSWindow windowWithContentViewController:] + 57 17 SwiftUI 0x7ff9199cd634 specialized WindowStyle.makeWindow(:) + 42 18 SwiftUI 0x7ff919b6c724 AnyWindowStyleStorage.makeWindow(:) + 26 19 SwiftUI 0x7ff91974a736 AppWindowsController.makeWindowController(:restorationID:environment:) + 2314 20 SwiftUI 0x7ff91974887d AppWindowsController.makeMainWindow(info:) + 66 21 SwiftUI 0x7ff9197487c7 AppWindowsController.makeMainWindow() + 424 22 SwiftUI 0x7ff919748067 AppWindowsController.showInitialMainWindow() + 82 23 SwiftUI 0x7ff9194e0c3e AppDelegate.applicationDidFinishLaunching(:) + 85 24 SwiftUI 0x7ff9194e0dd6 @objc AppDelegate.applicationWillFinishLaunching(_:) + 114 25 CoreFoundation 0x7ff80e9a6f23 CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER + 12 26 CoreFoundation 0x7ff80ea443f9 ___CFXRegistrationPost_block_invoke + 49 27 CoreFoundation 0x7ff80ea44376 _CFXRegistrationPost + 496 28 CoreFoundation 0x7ff80e978836 _CFXNotificationPost + 733 29 Foundation 0x7ff80f7c01be -[NSNotificationCenter postNotificationName:object:userInfo:] + 82 30 AppKit 0x7ff8113e761b -[NSApplication _postDidFinishNotification] + 305 31 AppKit 0x7ff8113e736d -[NSApplication _sendFinishLaunchingNotification] + 208 32 AppKit 0x7ff8113e4f40 -[NSApplication(NSAppleEventHandling) _handleAEOpenEvent:] + 541 33 AppKit 0x7ff8113e4b97 -[NSApplication(NSAppleEventHandling) _handleCoreEvent:withReplyEvent:] + 665 34 Foundation 0x7ff80f7eb194 -[NSAppleEventManager dispatchRawAppleEvent:withRawReply:handlerRefCon:] + 308 35 Foundation 0x7ff80f7eb006 _NSAppleEventManagerGenericHandler + 80 36 AE 0x7ff815043d28 0x7ff815038000 + 48424 37 AE 0x7ff815043592 0x7ff815038000 + 46482 38 AE 0x7ff81503c9c7 aeProcessAppleEvent + 419 39 HIToolbox 0x7ff8175fdc42 AEProcessAppleEvent + 54 40 AppKit 0x7ff8113df222 DPSNextEvent + 2064 41 AppKit 0x7ff8113dd3f4 -[NSApplication(NSEvent) nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1411 42 AppKit 0x7ff8113cf919 -[NSApplication run] + 586 43 AppKit 0x7ff8113a37b7 NSApplicationMain + 816 44 SwiftUI 0x7ff9191dad3f specialized runApp(:) + 161 45 SwiftUI 0x7ff919bf9c84 runApp(:) + 164 46 SwiftUI 0x7ff91970191f static App.main() + 63 47 MySwiftAPP 0x10c6be9ae 0x10c61d000 + 661934 48 dyld 0x1134d64fe start + 462 Thread 1: 0 libsystem_pthread.dylib 0x7ff80e8e5fec start_wqthread + 0 Thread 0 crashed with X86 Thread State (64-bit): rax: 0x0000000200000003 rbx: 0x00007f8db5915210 rcx: 0xfffffffe00000000 rdx: 0x0000000000000003 rdi: 0x00007f8db586b178 rsi: 0x00007ff8518bbf58 rbp: 0x00007ff7b38e0080 rsp: 0x00007ff7b38e0000 r8: 0x0000000000000002 r9: 0x80000000ffffffff r10: 0xfffffffe00000000 r11: 0x0000000000000001 r12: 0x00007f8db586b170 r13: 0x00007f8db586bb40 r14: 0x00007f8db586b290 r15: 0xe800000000000000 rip: 0x000000010c6df5bb rfl: 0x0000000000010297 cr2: 0x00007ff8510288e8 Logical CPU: 0 Error Code: 0x00000000 Trap Number: 6
2
0
156
3w
Getting path of deleted item from Scripting Bridge SBObject in Swift
In the Swift function at the end of this post, I use Scripting Bridge to have Finder delete a path. The variable result is a SBObject returned by the delete() function. I know that result somehow contains the new path of the deleted item in the trash folder, but I don't know how to nicely extract it as a single String. If I print(String(describing: result)), I get output like: <SBObject @0x0123456789ab: <class 'appf'> "AppName.app" of <class 'cfol'> ".Trash" of <class 'cfol'> "user" of <class 'cfol'> "Users" of startupDisk of application "Finder" (822)> Is there any way to obtain the String "/Users/user/.Trash/AppName.app" from result without having to perform string parsing on the above output? The Finder* types in the code below are from https://github.com/tingraldi/SwiftScripting/blob/master/Frameworks/FinderScripting/FinderScripting/Finder.swift func trash(path: String) throws { guard let finder: FinderApplication = SBApplication(bundleIdentifier: "com.apple.finder") else { throw runtimeError("Failed to obtain Finder access: com.apple.finder does not exist") } guard let items = finder.items else { throw runtimeError("Failed to obtain Finder access: finder.items does not exist") } let object = items().object(atLocation: URL(fileURLWithPath: path)) guard let item = object as? FinderItem else { throw runtimeError( """ Failed to obtain Finder access: finder.items().object(atLocation: URL(fileURLWithPath: \ \"\(path)\") is a '\(type(of: object))' that does not conform to 'FinderItem' """ ) } guard let delete = item.delete else { throw runtimeError("Failed to obtain Finder access: FinderItem.delete does not exist") } let result = delete() }
2
0
209
3w
SwiftData updates in the background are not merged in the main UI context
Hello, SwiftData is not working correctly with Swift Concurrency. And it’s sad after all this time. I personally found a regression. The attached code works perfectly fine on iOS 17.5 but doesn’t work correctly on iOS 18 or iOS 18.1. A model can be updated from the background (Task, Task.detached or ModelActor) and refreshes the UI, but as soon as the same item is updated from the View (fetched via a Query), the next background updates are not reflected anymore in the UI, the UI is not refreshed, the updates are not merged into the main. How to reproduce: Launch the app Tap the plus button in the navigation bar to create a new item Tap on the β€œUpdate from Task”, β€œUpdate from Detached Task”, β€œUpdate from ModelActor” many times Notice the time is updated Tap on the β€œUpdate from View” (once or many times) Notice the time is updated Tap again on β€œUpdate from Task”, β€œUpdate from Detached Task”, β€œUpdate from ModelActor” many times Notice that the time is not update anymore Am I doing something wrong? Or is this a bug in iOS 18/18.1? Many other posts talk about issues where updates from background thread are not merged into the main thread. I don’t know if they all are related but it would be nice to have 1/ bug fixed, meaning that if I update an item from a background, it’s reflected in the UI, and 2/ proper documentation on how to use SwiftData with Swift Concurrency (ModelActor). I don’t know if what I’m doing in my buttons is correct or not. Thanks, Axel import SwiftData import SwiftUI @main struct FB_SwiftData_BackgroundApp: App { var body: some Scene { WindowGroup { ContentView() .modelContainer(for: Item.self) } } } struct ContentView: View { @Environment(\.modelContext) private var modelContext @State private var simpleModelActor: SimpleModelActor! @Query private var items: [Item] var body: some View { NavigationView { VStack { if let firstItem: Item = items.first { Text(firstItem.timestamp, format: Date.FormatStyle(date: .omitted, time: .standard)) .font(.largeTitle) .fontWeight(.heavy) Button("Update from Task") { let modelContainer: ModelContainer = modelContext.container let itemID: Item.ID = firstItem.persistentModelID Task { let context: ModelContext = ModelContext(modelContainer) guard let itemInContext: Item = context.model(for: itemID) as? Item else { return } itemInContext.timestamp = Date.now.addingTimeInterval(.random(in: 0...2000)) try context.save() } } .buttonStyle(.bordered) Button("Update from Detached Task") { let container: ModelContainer = modelContext.container let itemID: Item.ID = firstItem.persistentModelID Task.detached { let context: ModelContext = ModelContext(container) guard let itemInContext: Item = context.model(for: itemID) as? Item else { return } itemInContext.timestamp = Date.now.addingTimeInterval(.random(in: 0...2000)) try context.save() } } .buttonStyle(.bordered) Button("Update from ModelActor") { let container: ModelContainer = modelContext.container let persistentModelID: Item.ID = firstItem.persistentModelID Task.detached { let actor: SimpleModelActor = SimpleModelActor(modelContainer: container) await actor.updateItem(identifier: persistentModelID) } } .buttonStyle(.bordered) Button("Update from ModelActor in State") { let container: ModelContainer = modelContext.container let persistentModelID: Item.ID = firstItem.persistentModelID Task.detached { let actor: SimpleModelActor = SimpleModelActor(modelContainer: container) await MainActor.run { simpleModelActor = actor } await actor.updateItem(identifier: persistentModelID) } } .buttonStyle(.bordered) Divider() .padding(.vertical) Button("Update from View") { firstItem.timestamp = Date.now.addingTimeInterval(.random(in: 0...2000)) } .buttonStyle(.bordered) } else { ContentUnavailableView( "No Data", systemImage: "slash.circle", // τ€•§ description: Text("Tap the plus button in the toolbar") ) } } .toolbar { ToolbarItem(placement: .primaryAction) { Button(action: addItem) { Label("Add Item", systemImage: "plus") } } } } } private func addItem() { modelContext.insert(Item(timestamp: Date.now)) try? modelContext.save() } } @ModelActor final actor SimpleModelActor { var context: String = "" func updateItem(identifier: Item.ID) { guard let item = self[identifier, as: Item.self] else { return } item.timestamp = Date.now.addingTimeInterval(.random(in: 0...2000)) try! modelContext.save() } } @Model final class Item: Identifiable { var timestamp: Date init(timestamp: Date) { self.timestamp = timestamp } }
0
1
325
3w
Cannot remove languages from Swift string catalog
I've got quite a problem as I've created a Localizible file with String catalog for my iOS app. For testing it out I've added lots of different languages and they all appeared in App settings. However, I need to remove most of them and they are still visible in the settings. What I tried so far: I have deleted EVERYTHING that had word localizable, localizations and etc. From Project Info also all the languages were removed and left only English and French. I also deleted my app, restarted the phone, downloaded the version without localizations from the app store and then install debug version (languages still appeared)
0
0
163
4w