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

UIPasteControl Button Appearing Disabled but Still Pasting Content
Hi everyone, I've implemented a UIPasteControl in my iOS app using the following code: func displayPasteControl() { if #available(iOS 16.0, *) { let pasteControlConfig = UIPasteControl.Configuration() let newPasteControlButton = UIPasteControl(configuration: pasteControlConfig) self.inputContainerView.addSubview(newPasteControlButton) newPasteControlButton.isEnabled = true // Set constraints for this button newPasteControlButton.translatesAutoresizingMaskIntoConstraints = false newPasteControlButton.topAnchor.constraint(equalTo: self.originalPasteView.topAnchor, constant: 0).isActive = true newPasteControlButton.centerXAnchor.constraint(equalTo: self.inputContainerView.centerXAnchor).isActive = true newPasteControlButton.widthAnchor.constraint(equalTo: self.originalPasteView.widthAnchor, multiplier: 0.5).isActive = true newPasteControlButton.bottomAnchor.constraint(equalTo: self.originalPasteView.bottomAnchor, constant: 0).isActive = true newPasteControlButton.target = self.inputTextView } } I call this function in viewWillAppear: override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) displayPasteControl() } Sometimes, I've noticed that the UIPasteControl button appears in a disabled state visually, but when I press it, the content from the clipboard is still pasted. I checked the state of UIPasteControl and it indicates that it is in an enabled state. For context, the UIPasteControl target is set to a UITextView (self.inputTextView). Has anyone experienced this issue or have any idea why this might be happening? Any help would be appreciated! Thank you!
0
0
114
Jun ’24
Using Cloud Storage With SwiftData Custom Data Store
The following videos from WWDC24 say that we can use cloud storage for our SwiftData stores. Video references below: What's new in SwiftData Create a custom data store with SwiftData When watching the videos it shows examples of how we can read and write to a JSON file as a store, rather than using the built in store that comes with SwiftData. But there are mentions that we can use cloud storage like a backend i.e. a database hosted on a server. The only thing that I'm struggling to figure out and it would be great if we had code samples for this is how to achieve using cloud storage as a store since looking at the current implementations of: DataStoreConfiguration DataStore The required functions we need to implement look synchronous rather than asynchronous so how would or could we handle fetching asynchronous data from cloud storage. So how would we handle this? Also it would be great if someone could clarify how or if there is a way to send notifications for changes to your store between different devices similar to CloudKit? Are there there any plans to provide more documentation & sample code for the questions I've asked above? Feedback FB13857743
1
3
262
Jun ’24
Get time it took to complete HMCharacteristic.writeValue()
I'm working on an app that uses HomeKit-enabled accessories such as wall plugs to control a photographic enlarger in a darkroom. This requires precise timing when toggling the power state of the plug. For example, the timer in my app might be set to 5 seconds, so I turn on the plug using writeValue() on the plugs power state characteristic, wait 5 seconds, then turn it off again. I want to be able to measure if the plug actually responded to the command and if there was any delay in the plug actually turning on/off so I can display a warning to the user if network latency resulted in the plug being on for longer than the set time. Does writeValue() (in my case, the async/await version) only return when the plug has been turned on, or does it return as soon as the command has been sent, regardless of if it has been received/acted on? Is there a way I can (a) quickly verify that the plug has been turned on/off, and (b) measure how long it took for the plug to act on the request, that is, the time elapsed between when writeValue() is called and when the plug actually updates to the corresponding value?
0
0
230
Jun ’24
UIDevice: Main actor-isolated class property 'current' can not be referenced from a non-isolated context
I have a Safari Web Extension for visionOS that reads from UIDevice.current.systemVersion in order to provide the OS version number back to the JavaScript context utilizing beginRequest(with:). When switching my project to use Swift 6, I received this obscure error: Main actor-isolated class property 'current' can not be referenced from a non-isolated context Class property declared here (UIKit.UIDevice) Add '@MainActor' to make instance method 'beginRequest(with:)' part of global actor 'MainActor' Adding @MainActor causes another issue (Main actor-isolated instance method 'beginRequest(with:)' cannot be used to satisfy nonisolated protocol requirement) which suggests adding @preconcurrency to NSExtensionRequestHandling which then breaks at Non-sendable type 'NSExtensionContext' in parameter of the protocol requirement satisfied by main actor-isolated instance method 'beginRequest(with:)' cannot cross actor boundary. What's the proper solution here? Here's a simplified snippet of my code: class SafariWebExtensionHandler: NSObject, NSExtensionRequestHandling { func beginRequest(with context: NSExtensionContext) { // ... var systemVersionNumber = "" systemVersionNumber = UIDevice.current.systemVersion // ... } }
1
0
332
Jun ’24
SwiftUI NavigationLink destination
In truth, I do not fully understand JSON Files and I am new to Swift. I am trying to be a bit too clever and build my menu from a JSON file. [ { "description": "Readings Entry", "target": "ReadingsEntry", "icon": "barometer", }, { "description": "Readings Entry", "target": "ReadingsView()", "icon": "tablecells.badge.ellipsis", }, { "description": "Food Diary", "target": "FoodDiary()", "icon": "fork.knife.circle", }, { "description": "Readings Entry", "target": "Settings()", "icon": "gearshape", } ] Because I don't know any better I have stored the destination view (target) as a String in the "struct" that I have constructed to import the JSON data. import SwiftUI struct dcMenu: Codable, Identifiable { enum CodingKeys: CodingKey { case description case target case icon } var id = UUID() var description: String var target: String var icon: String } class ReadData: ObservableObject { @Published var lineText = [dcMenu]() init(){ loadData() } func loadData() { guard let url = Bundle.main.url(forResource: "menu", withExtension: "json") else { print("Json file not found") return } let data = try? Data(contentsOf: url) let lineText = try? JSONDecoder().decode([dcMenu].self, from: data!) self.lineText = lineText! } } But the issue this leaves me with is when I come to construct the actual menu, How do I use the string "target" as the "destination" of the navigation link? struct ContentView: View { @ObservedObject var menuLines = ReadData() var body: some View { NavigationSplitView { . . . List(menuLines.lineText) { lines in NavigationLink(destination: lines.target){ Image(systemName: lines.icon) Text(lines.description) } } . . . .navigationSplitViewColumnWidth(min: 75, ideal: 100) } detail: { . . . } .navigationTitle("Diabetes Control") } }
2
0
220
Jun ’24
Why is the `TipViewStyle` protocol not isolated to the main actor?
Hey, the TipViewStyle protocol seems to still be nonisolated, which makes using it in the Swift 6 language mode impossible, I believe (at least without using something like MainActor.assumeIsolated): @available(macOS 14.0, iOS 17.0, tvOS 17.0, visionOS 1.0, watchOS 10.0, *) public protocol TipViewStyle { // ... } I cannot use any views inside the makeBody method. Other style protocols, like ButtonStyle are correctly isolated to the main actor: @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) @MainActor @preconcurrency public protocol ButtonStyle { // ... } Is this just an oversight or am I missing something and this is actually intentional? Thanks!
2
0
185
Jun ’24
Proper way to use IOKit in iOS app?
Hello, forum, I'm trying to build connection between a non-MFi HID device (like keyboard) and iOS app with IOKit and Swift. Thanks to this post, I have manage to import the IOKit into objc header. IOKit on iOS/iPadOS 16.0+ #import <IOKit/IOKitLib.h> However, I have this compiler error when I try to imitate same methods in the SerialPortSaple project from following article, but the IOKit can not be imported to Swift at first place. Communicating with a Modem on a Serial Port The screen shot of the sample project: It looks like the complier unable to reach the io_object_t type somehow, is there any workaround or approach?
4
0
394
Jun ’24
macOS app crashes on first launch from TestFlight
2024_06_09_testflight_launch_crash_log.txt Running my macOS app the first time after installing via TestFlight crashes on launch. Every subsequent run works fine (including completely quitting the app and re-running it). Also, building and running directly in XCode both in Debug and Release mode works fine. I'm on a Mac M2 and the app excludes x86_64 arch. Here is the trimmed crash log (sanitised full log is attached) Crashed Thread: 0 Dispatch queue: com.apple.main-thread Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x0000000000000000, 0x0000000000000000 Termination Reason: Namespace SIGNAL, Code 6 Abort trap: 6 Terminating Process: CamHero-macOS-v2-Release [12876] Application Specific Information: abort() called Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 libsystem_kernel.dylib 0x18c81d11c __pthread_kill + 8 1 libsystem_pthread.dylib 0x18c854cc0 pthread_kill + 288 2 libsystem_c.dylib 0x18c764a40 abort + 180 3 libglib-2.0.0.dylib 0x1061e5bd0 g_assertion_message + 464 4 libglib-2.0.0.dylib 0x1061e5c44 g_assertion_message_expr + 116 5 libgstlibav.dylib 0x10549ede0 gst_ffmpeg_cfg_init + 776 6 libgstlibav.dylib 0x10548a4f4 plugin_init + 140 7 libgstreamer-1.0.0.dylib 0x10646a458 gst_plugin_register_func + 636 8 libgstreamer-1.0.0.dylib 0x106469fe4 gst_plugin_register_static + 212 9 libgstlibav.dylib 0x10548a45c gst_plugin_libav_register + 92 10 CamHero-macOS-v2-Release 0x104a01624 gst_ios_init + 900 (gst_ios_init.m:1072) 11 CamHero-macOS-v2-Release 0x104a80590 specialized CamHeroMacOSApp.init() + 68 (CamHeroMacOSApp.swift:19) 12 CamHero-macOS-v2-Release 0x104a804a4 CamHeroMacOSApp.init() + 4 [inlined] 13 CamHero-macOS-v2-Release 0x104a804a4 protocol witness for App.init() in conformance CamHeroMacOSApp + 20 (<compiler-generated>:16) 14 SwiftUI 0x1b7f134e0 0x1b7163000 + 14353632 15 CamHero-macOS-v2-Release 0x104a804d8 static CamHeroMacOSApp.$main() + 24 [inlined] 16 CamHero-macOS-v2-Release 0x104a804d8 main + 36 17 dyld 0x18c4d90e0 start + 2360 Thread 1: 0 libsystem_pthread.dylib 0x18c84fe28 start_wqthread + 0 Thread 2: 0 libsystem_pthread.dylib 0x18c84fe28 start_wqthread + 0 Thread 0 crashed with ARM Thread State (64-bit): x0: 0x0000000000000000 x1: 0x0000000000000000 x2: 0x0000000000000000 x3: 0x0000000000000000 x4: 0x0000600000755680 x5: 0x0000000000000020 x6: 0x0000600000755680 x7: 0xffffffff00008600 x8: 0x8ddd1ea266cd729b x9: 0x8ddd1ea3846d2c5b x10: 0x0000000000001620 x11: 0x00000000dbe367fb x12: 0x00000000000007fb x13: 0x00000000000007fd x14: 0x00000000dc03683c x15: 0x000000000000003c x16: 0x0000000000000148 x17: 0x00000001eb9f3da0 x18: 0x0000000000000000 x19: 0x0000000000000006 x20: 0x00000001e2a05ec0 x21: 0x0000000000000103 x22: 0x00000001e2a05fa0 x23: 0x000000016b407508 x24: 0x0000000000000000 x25: 0x00000001064f8450 x26: 0x000060000080d511 x27: 0x0000000000000000 x28: 0x0000000000000000 fp: 0x000000016b407460 lr: 0x000000018c854cc0 sp: 0x000000016b407440 pc: 0x000000018c81d11c cpsr: 0x40001000 far: 0x0000000000000000 esr: 0x56000080 Address size fault It seems that the initialisation of one of the gstreamer plug-ins doesn't go well. But, I wonder what might lead to that happening only the first time after launch? Will appreciate any clues! EDIT / UPDATE: If i remove the app completely and install the same version again from TestFlight, app doesn't crash. So it seems the crashing is limited to the very first launch of a new /updated version.
3
0
385
3w
representation error in swift generated header
I have a public swift function with the below declaration : public func InternalMain (_ pNumOfArgs : Int32, _ pCmdlineArgs : UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>) -> Int32 {..} I need this function as public because I need to invoke in from a different library. But the above declaration produces an error in my generated swift header i.e '-swift.h' file because 'UnsafeMutablePointer<UnsafeMutablePointer?>' type cannot be represented in the swift generated header. Can someone help how do I get past this. This is a class independent function and I tried using the '@nonobj' to prevent this from getting in the generated header but it still gives an error.
2
0
384
Jun ’24
SwiftUI List and ForEach
What have I done wrong? I am trying to "List" a set of string values from an array, I spent all day trying to get it to work. What have I done wrong? import SwiftUI struct ContentView: View { @State private var menuItems = ["Settings", "Readings Entry", "Food Diary"] @State private var targets = ["Settings()", "ReadingsEntry()", "FoodDiary()"] var body: some View { NavigationStack { List { ForEach(menuItems) { menuLine in print(menuLine) } }.navigationTitle("Menu") } } } The latest set of Error messages are: Against the ForEach Line : Cannot convert value of type '[String]' to expected argument type 'Range' Against the print line3: Type '()' cannot conform to 'View'
2
0
292
Jun ’24
get the error even though enabled Hardened Runtime
Hello there. I'm having trouble with notarization in Xcode. I'm developing a Swift Mac app with Xcode 14, but even when I enable Hardened Runtime and perform notarization, it displays the message "Hardened Runtime is not enabled" and I can't proceed. The steps for notarization are [Window] -> [Organizer] -> [Distribute App] -> [Developer ID] [Next] -> [Upload]. Could you please tell me what I should check, or any other information? I've attached screenshots. Thank you.
1
0
345
Jun ’24
Can't typing on NSTextField
Hi, I just did a NSTextField with auto complete that show a cities menu bar the problem is when I typing the first letter, the focus change to the menubar and if I try to write another letter it just replace the first letter and not add it how can I fix it? Thank you! class NSTextFieldAuto: NSTextField, NSMenuDelegate, NSTextFieldDelegate { var suggestionMenu: NSMenu? var selectedSuggestionIndex: Int? override func awakeFromNib() { super.awakeFromNib() self.delegate = self self.suggestionMenu = NSMenu() self.suggestionMenu?.delegate = self } override func mouseDown(with event: NSEvent) { super.mouseDown(with: event) // Deselect all text when the text field is clicked } override func textDidChange(_ notification: Notification) { super.textDidChange(notification) print("Still typing") updateSuggestionMenu() showSuggestionMenu() } override func textDidEndEditing(_ notification: Notification) { print("Finished typing") cityDef.setValue(self.stringValue, forKey: cityDefKey) } func updateSuggestionMenu() { self.suggestionMenu?.removeAllItems() let searchText = self.stringValue.lowercased() for (index, city) in allCities.enumerated() { if city.lowercased().hasPrefix(searchText) { let item = NSMenuItem(title: city, action: #selector(selectSuggestion(_:)), keyEquivalent: "") item.target = self self.suggestionMenu?.addItem(item) } } } func showSuggestionMenu() { if let menu = self.suggestionMenu, !menu.items.isEmpty { let textFieldRect = self.bounds let origin = NSPoint(x: textFieldRect.origin.x + 100.0, y: textFieldRect.origin.y + textFieldRect.size.height) menu.autoenablesItems = false menu.popUp(positioning: nil, at: origin, in: self) } } @objc func selectSuggestion(_ sender: NSMenuItem) { self.stringValue = sender.title } override func cancelOperation(_ sender: Any?) { self.suggestionMenu?.cancelTracking() self.window?.becomeFirstResponder() } func menuDidClose(_ menu: NSMenu) { self.window?.makeFirstResponder(self) // Set text field as first responder again print("Close menu") } override func becomeFirstResponder() -> Bool { let result = super.becomeFirstResponder() self.selectedSuggestionIndex = nil // Reset selected suggestion index return result } }
3
0
296
Jun ’24
Safari App Extension remove toolbar item - Mac
Hi, I have built a Safari App Extension for Mac. However, I want to remove the toolbar item from the extension. I have tried the following approach: Remove SFSafariToolbarItem dictionary from Info.plist Remove the toolbar icon pdf from the project Remove validateToolbarItem and popoverViewController from the extension handler. This does not remove the toolbar item. Instead I have a toolbar item that shows my App Icon just greyed out. On clicking that item, it show an option to "Manage Extension". What should I do to remove the toolbar item from my extension?
1
0
328
Jun ’24
How to display "Return to app" option in the "Return to Clock" watch menu?
I have a sports iOS app with a paired watch app, that uses location to update some UI elements. I technically need the location only when the watch app is in foreground, but since another requirement is to stop the clock from replacing the app, I decided to add background location checks. I followed the steps from the documentation (adding Background Modes to the watch extension target, setting allowsBackgroundLocationUpdates to true): the location update works fine when I go to the clock, the app's icon is displayed in a circle at the top (bringing the app back to foreground on tap). The only problem is that the "Return to app" option in the "Return to Clock" settings menu is missing, what do I need to do in order to display it? Here's an example of what it looks like for the Strava app: and how it looks for mine.
2
0
348
3w
Push notification not working with production environment
Hey Team, We're experiencing an issue where push notifications are failing to deliver to certain devices in the production environment. However, they are working fine in the development build on specific devices. Interestingly, the notifications are working fine for a few devices in the same production environment. In the affected devices we have attempted the following things to resolve the issue Verify the device token (& send the notification through apple push notification console) reinstall the application reboot the device Below are the device details Model - Macbook Pro 15-inch, 2018 processor - 2.9 GHz 6-Core Intel Core i9 OS Version - macOS Sonoma 14.2.1 I have attached the APSD process console log for the affected device. In which we are getting following error. apsd Peer connection [pid=472] lacks APSConnectionInitiateEntitlement APSD_ConsoleLog.txt Thank you all in advance for any information regarding this issue and we will provide any additional information if needed.
1
0
279
Jun ’24
Archiving my macOS target app fails with BOOL error
I'm building a macOS target for my App (which also has some Obj-C code). Building and running the app is fine but when I archive the app in XCode, the process / build fails with the following error Type 'BOOL' (aka ;Int32') cannot be used as a boolean;test for '!=0' instead It happens in a couple of places, one of the places being private func getRootDirectory(createIfNotExists: Bool = true) throws -> URL { return try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) } where it complains that create: true is not acceptable and throws the above error. If I comment out this line, the archive works successfully. When i Cmd + click the definition of Filemanager.default.url , i get this @available(macOS 10.6, *) open func url(for directory: FileManager.SearchPathDirectory, in domain: FileManager.SearchPathDomainMask, appropriateFor url: URL?, create shouldCreate: BOOL) throws -> URL This looks fishy since it it says create shouldCreate: BOOL whereas the documentation says it should be just Bool func url( for directory: FileManager.SearchPathDirectory, in domain: FileManager.SearchPathDomainMask, appropriateFor url: URL?, create shouldCreate: Bool ) throws -> URL My minimum deployment target is macOS 13.0 I'm quite stumped at this error - which happens only while archiving. Does anybody know why?
4
0
396
Jun ’24
Seeking Advice on Real-Time Heartbeat Data from Apple Watch: Heart Rate vs. HKElectrocardiogram
Hello, I am developing an Apple Watch app in Swift and SwiftUI that needs to receive real-time heartbeat data to visualize the time intervals between heartbeats. The app draws circles on the screen where the size and position of each circle are based on the time interval between consecutive heartbeats. I am currently using the HKQuantityType for .heartRate from HealthKit to get heart rate data and calculate the intervals. However, I am wondering if this is the best approach for my requirement. I came across the HKElectrocardiogram class, and I am not sure if it would be a better fit for obtaining real-time heartbeat intervals. My questions are: Real-Time Heartbeats: Is HKQuantityType for .heartRate the most appropriate way to get real-time heartbeat data for calculating intervals between beats? Can HKElectrocardiogram provide real-time heartbeat intervals, or is it more suited for detailed ECG recordings rather than instantaneous heartbeats? Accuracy and Performance: Which method provides the most accurate and real-time data for heartbeat intervals? Are there any other APIs or services in the Apple Watch ecosystem that I should consider for this purpose? Best Practices: What are the best practices for implementing real-time heartbeat monitoring in an Apple Watch app? Are there any sample projects or documentation that could help me understand the optimal way to achieve this? Here is a brief overview of my current implementation using HKQuantityType for .heartRate: import Foundation import HealthKit class HeartRateMonitor: NSObject, ObservableObject { @Published var heartRate: Double = 0.0 @Published var intervals: [TimeInterval] = [] private var lastHeartRateTimestamp: Date? private var healthStore: HKHealthStore? private let heartRateQuantityType = HKObjectType.quantityType(forIdentifier: .heartRate) private let appStartTime: Date override init() { self.appStartTime = Date() super.init() if HKHealthStore.isHealthDataAvailable() { self.healthStore = HKHealthStore() self.requestAuthorization() } } private func requestAuthorization() { guard let heartRateQuantityType = self.heartRateQuantityType else { return } healthStore?.requestAuthorization(toShare: nil, read: [heartRateQuantityType]) { success, error in if success { self.startMonitoring() } } } func startMonitoring() { guard let heartRateQuantityType = self.heartRateQuantityType else { return } let query = HKAnchoredObjectQuery( type: heartRateQuantityType, predicate: nil, anchor: nil, limit: HKObjectQueryNoLimit) { (query, samples, deletedObjects, newAnchor, error) in guard let samples = samples as? [HKQuantitySample] else { return } self.process(samples: samples) } query.updateHandler = { (query, samples, deletedObjects, newAnchor, error) in guard let samples = samples as? [HKQuantitySample] else { return } self.process(samples: samples) } healthStore?.execute(query) } private func process(samples: [HKQuantitySample]) { for sample in samples { if sample.endDate > appStartTime { let heartRateUnit = HKUnit.count().unitDivided(by: HKUnit.minute()) let heartRate = sample.quantity.doubleValue(for: heartRateUnit) DispatchQueue.main.async { self.heartRate = heartRate if let lastTimestamp = self.lastHeartRateTimestamp { let interval = sample.endDate.timeIntervalSince(lastTimestamp) self.intervals.append(interval) } self.lastHeartRateTimestamp = sample.endDate } } } } } Thank you for your guidance and suggestions!
1
0
438
Jun ’24