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

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
255
2w
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
191
2w
How might I get didSet behaviour on an AppStorage var?
I've defined a value stored in UserDefaults. In a view struct I have code that can successfully update the stored value. I've also added an @AppStorage var in an instance of a class, that can read this value and run business logic that depends on the current stored value. But what I really want to do, is have code in my class that gets automatically called when the value stored in UserDefaults gets updated. Basically I want to do this: @AppStorage("languageChoice") var languageChoice: LanguageChoice = .all { didSet { print("hello") } } Unfortunately didSet closures in @AppStorage vars do not appear to get called :-( My clumsy attempts to use combine have all ended in tears from the compiler. Any/all suggestions are greatly appreciated. thanks, Mike
3
0
288
3w
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
291
3w
Wallet Extension - "From apps on your iPhone" option not showing
I'm implementing Wallet Extension for adding credit card on wallet, I created both extension, UI and NonUI, but the "From apps on your iPhone" option never shows to me. My extensions have the same entitlements of main app, with the com.apple.developer.payment-pass-provisioning. My NonUI status function implementation: final class MBFApplePayNonUIExtensionHandler: PKIssuerProvisioningExtensionHandler { override func status(completion: @escaping (PKIssuerProvisioningExtensionStatus) -> Void) { let status = PKIssuerProvisioningExtensionStatus() status.requiresAuthentication = true status.passEntriesAvailable = true status.remotePassEntriesAvailable = true completion(status) } .... I tried this to: final class MBFApplePayNonUIExtensionHandler: PKIssuerProvisioningExtensionHandler { override func status(completion: @escaping (PKIssuerProvisioningExtensionStatus) -> Void) { let status = PKIssuerProvisioningExtensionStatus() status.requiresAuthentication = true completion(status) } .... Extensions .plists: NonUI: NSExtension NSExtensionPointIdentifier com.apple.PassKit.issuer-provisioning NSExtensionPrincipalClass MBFApplePayNonUIExtensionHandler UI: NSExtension NSExtensionMainStoryboard MBFApplePayUIExtension NSExtensionPointIdentifier com.apple.PassKit.issuer-provisioning.authorization What am I missing?
4
0
2.1k
3w
How to set timeFormat of DatePicker in swift
DatePicker always get timeFormat from device setting, but i need to show time in datePicker based on My app setting not device setting. any solution for this problem I tried to set locale "us_POSIX" locale for 12 hour and "us_GB" for 24 hour format this way is work in gregorian calendar , but in japanese calendar not showing year properly like (picker showing " 6 " instead of " Reiwa 6 " )
4
0
268
3w
XPC, Swift, ObjC, and arrays
I create a protocol that had, among other things: @objc func setList(_: [MyType], withReply: @escaping (Error?) -> Void) The daemon part is in Swift, while the calling part is in Objective-C. Because why not? (Actually, because the calling part has to deal with C++ code, so that's ObjC++; however, I wanted the stronger typing and runtime checking for the daemon part, so I wrote it in Swift.) The ObjC part uses NSArray<MyType*>. I set up an NSXPCConnection link, and create a (synchronous) proxy with the right protocol name. But when I try to do the XPC setList call, I get an error. I assume that's because it doesn't like the signature. (Surely this is logged somewhere? I couldn't find it, if so. 😩) But... if I have a signature of @objc func addItem(_: MyType, withReply: @escaping (Error?) -> Void), then it works. So I assume it's the array. (Oh, I've also tried it without the @objc; the protocol itself is defined as @objc.) I've tried changing to protocol signature to using NSArray, but same thing.
7
0
1k
3w
Xcode 13 typing is delayed / really slow
I just updated Xcode to the newest Version (13.0 13A233). And what I immediately recognized was that when I was typing in a large class (1000 Lines or more) the typing was delayed like 1 or 2 seconds. This makes it really hard to type or even do anything with my project. It works perfectly fine in smaller projects with only 100 Code Lines per File, but it is really hard to type in bigger projects with over 30 files and 3000 Code Lines per File. This always happens when I use Xcode, whether I run the app on a real device or a simulator. Things that could cause the issue in my case: I removed the contents of ~/Library/Developer/Xcode/iOS DeviceSupport, because it took the device previously too long to launch, but I don´t think that this should have an effect on my Xcode typing performance. I would really appreciate any help, because this issue makes my work impossible and really concerns me a lot.
52
3
19k
3w
SwiftUI does not manage two NavigationLinks in a single list row
There seems to be a problem with placing multiple NavigationLinks on a List item row in SwiftUI. If I have two links on the same row and tap one of them, SwiftUI seems to create a path using both links. Irrespective of which of the two is tapped, the view specified by the first (left-hand) appears. Tapping Back reveals the view specified by the second (right-hand) link. Tapping again returns to the list. This problem has been mentioned before in relation to Buttons. The solution offered was to use button styles, and make sure the button areas do not overlap (how could they overlap?). This does not work ChatGPT gave me a clear example, which it claimed would work, but just demonstrates the problem import SwiftUI struct ContentView: View { var body: some View { NavigationView { List { ForEach(0..<10) { index in HStack { NavigationLink(destination: DestinationView1(item: index)) { Text("Navigate to View 1") .padding() .background(Color.blue) .foregroundColor(.white) .cornerRadius(8) } .buttonStyle(PlainButtonStyle()) // Ensure the link only activates on its area Spacer() NavigationLink(destination: DestinationView2(item: index)) { Text("Navigate to View 2") .padding() .background(Color.green) .foregroundColor(.white) .cornerRadius(8) } .buttonStyle(PlainButtonStyle()) // Ensure the link only activates on its area } .padding(.vertical, 5) } } .navigationBarTitle("Navigation Links") } } } struct DestinationView1: View { var item: Int var body: some View { Text("Destination View 1 for item \(item)") .navigationBarTitle("View 1", displayMode: .inline) } } struct DestinationView2: View { var item: Int var body: some View { Text("Destination View 2 for item \(item)") .navigationBarTitle("View 2", displayMode: .inline)
6
0
309
3w
SwiftUI crash on macOS 10.13 and 10.14
Hi there, My macOS AppKit/Cocoa app uses Swift and Objective-C, however I'm not using SwiftUI anywhere. Customers launching the app now receive an instant crash due to dyld not being able to locate SwiftUI: Library not loaded: /System/Library/Frameworks/SwiftUI.framework/Versions/A/SwiftUI Again, not using SwiftUI anywhere in my app, cannot find any project references in Xcode that mention SwiftUI - yet checking the generated binary with otool reveals that my app indeed appears to link against SwiftUI. Any idea what happened..? Thanks, Jay
3
0
445
3w
Issues with playing 3D videos and adding additional views in VisionOs AvplayerViewController
I want to add additional UI to places outside of AVPlayerViewController, such as adding likes and comments, but I found that once AVPlayerViewController is wrapped in other views, it becomes inline mode and cannot play 3D effects, instead becoming 2D effects. 3D effects can only be played when it is full screen. I want to know if there is any way to meet my needs like this? On the premise of being able to play 3D videos, add additional layouts outside the AVPlayerViewController, or use AVPlayerViewController to achieve the method of both playing 3D videos and adding additional layouts outside the player. If anyone knows, could you give me some guidance? Thank you.
0
1
227
3w
How to open Passcode field in Swift XCTest UI with iOS 17.4
This code works when I run it in the iOS Simulator with iOS 17.0.1: let passcodeInput = springboard.secureTextFields["Passcode field"] _ = passcodeInput.waitForExistence(timeout: 10) passcodeInput.tap() However if I run it on the iOS Simulator with iOS 17.4 I get this error: t = nans Checking existence of `"Passcode field" SecureTextField` t = nans Capturing debug information t = nans Requesting snapshot of accessibility hierarchy for app with pid 66943 t = nans Tap "Passcode field" SecureTextField t = nans Wait for com.apple.springboard to idle t = nans Find the "Passcode field" SecureTextField t = nans Find the "Passcode field" SecureTextField (retry 1) t = nans Find the "Passcode field" SecureTextField (retry 2) t = nans Requesting snapshot of accessibility hierarchy for app with pid 66943 <unknown>:0: error: PRCheckUITests : Failed to tap "Passcode field" SecureTextField: No matches found for Descendants matching type SecureTextField from input {( Application, pid: 66943, label: ' ' )} Did the hardcoded string "Passcode field" change for iOS 17.4? How can I access the passcode field through springboard in a test?
1
0
346
3w
SwiftUI Picker Label
I have set up a "Picker" which works well, EXCEPT that the Label won't appear, I have struggled around this and I am sure the solution is very simple, here's what I have. import SwiftUI import SwiftData struct iPadReadingsEntry: View { @State private var whatOccasion: String = "" let occassions = ["Misc", "Breakfast", "Mid Day Meal", "Evening Meal", "Bed Time"] var body: some View { . . . HStack{ Picker("Before What Occasion :", selection: $whatOccasion ){ ForEach(occassions, id: \.self) { Text($0) } }.pickerStyle(MenuPickerStyle()) .background(Color(red: 255, green: 253, blue: 208)) Spacer() }.padding(.leading, 80) .padding(.bottom, 30) . . .
1
0
252
3w
HELP ME!!
I'm studying Swift programing with using Apple official document "Develop in Swift Tutorial" https://developer.apple.com/tutorials/develop-in-swift/. When I do that, I faced to some problems which I cannot resolve myself. So, could you help or advise me about it. Problem:I can't implement this program which this below text say. How do I write the code?? (This section is that "Wrap-up: Lists and Text fields, Develop in Swift Tutorials") Here's my current states... import SwiftUI struct ContentView: View { @State private var names: [String] = [] @State private var nameToAdd = "" @State private var pickedName = "" @State private var shouldRemovePickedName = false var body: some View { VStack { VStack(spacing: 8) { Image(systemName: "person.3.sequence.fill") .foregroundStyle(.tint) .symbolRenderingMode(.hierarchical) Text("Pick-a-Pal") } .font(.title) .bold() //3項条件演算子 Text(pickedName.isEmpty ? "" : pickedName) .font(.title2) .bold() .foregroundStyle(.tint) List { ForEach(names, id: \.self) { name in Text(name) } } .clipShape(RoundedRectangle(cornerRadius: 8)) TextField("Add Name", text: $nameToAdd) //単語の自動修正をオフにする .autocorrectionDisabled() .onSubmit { if !nameToAdd.isEmpty { names.append(nameToAdd) nameToAdd = "" } } Divider() Toggle("Remove when picked", isOn: $shouldRemovePickedName) Button { if let randomName = names.randomElement() { pickedName = randomName if shouldRemovePickedName { names.removeAll() { name in return (name == randomName) } } } else { pickedName = "" } } label: { Text("Pick Random Name") .padding(.vertical, 8) .padding(.horizontal, 16) } .buttonStyle(.borderedProminent) .font(.title2) } .padding() } } #Preview { ContentView() }
3
0
295
3w
Start live activity with push notification problem
Hey there, i implemented live activity in my app and iam trying to start the live activity from push notification, updates works fine even when the app is in background but starting the activity creating issue mostly on background and kill mode when i check the delivery of live activity on cloudkit console it says stored for device power considerations. anyone having the same issue ?
0
0
242
3w
Swift: Navigation link not working.
I have obviously missed some subtle bit of code but I can't see what I am missing. I am getting a warning about my NavigationLink. Result of 'NavigationLink<Label, Destination>' initializer is unused Below I have included the code that has caused the warning and the code of the target of the Navigation link. The link does not work, though the button does, as proved by the print statement (see below). Here is the code that caused the warning: import SwiftUI import SwiftData struct Main_Menu_iPad: View { @Environment(\.modelContext) private var context @Query private var readings: [Readings] var body: some View { ZStack { Image("iPad Background 810 X 1060") .resizable() .scaledToFill() .ignoresSafeArea() VStack { HStack{ Image("Diabetes Control Logo 1024X1024") .resizable() .frame(width: 100, height: 100, alignment: .leading) .padding(.leading, 40) Text("Diabetes Control") .font(Font.custom("SnellRoundhand-Black", size: 40)) .background(Color(red: 255, green: 253, blue: 208)) .shadow(color: Color(red: 128, green: 128, blue: 128), radius: 3) .padding(.leading, 150) Spacer() }.padding(.bottom, 35) HStack { Text("What would you like to do : ") .font(Font.custom("SnellRoundhand-Black", size: 30)) .background(Color(red: 128, green: 128, blue: 128)) .shadow(color: Color(red: 126, green: 128, blue: 128), radius: 3) Spacer() }.padding(.leading, 35) .padding(.bottom,35) NavigationStack { HStack { Button { print("I have been pressed") NavigationLink { iPadReadingsEntry() } label: { Text("Enter a BLOOD Glucose reading") } } label: { Text("Enter a Blood Glucose Reading") }.background(Color(red: 255, green: 253, blue: 208)) .foregroundColor(.black) .font(Font.custom("SnellRoundhand", size: 24)) Spacer() }.padding(.leading, 60) .padding(.bottom, 25) Spacer() }.background(.blue) Spacer() } } } } #Preview { Main_Menu_iPad() } And this is the code of the target view: import SwiftUI struct iPadReadingsEntry: View { var body: some View { ZStack { Image("iPad Background 810 X 1060") .resizable() .scaledToFill() .ignoresSafeArea() VStack { HStack{ Image("Diabetes Control Logo 1024X1024") .resizable() .frame(width: 100, height: 100, alignment: .leading) .padding(.leading, 40) Text("Diabetes Control") .font(Font.custom("SnellRoundhand-Black", size: 40)) .background(Color(red: 255, green: 253, blue: 208)) .shadow(color: Color(red: 128, green: 128, blue: 128), radius: 3) .padding(.leading, 150) Spacer() }.padding(.bottom, 35) Spacer() } } } } #Preview { iPadReadingsEntry() } Finally is there a way of switching View without using a NavigationStack/NamigastinLink as it covers my background image?
1
0
256
3w
SwiftData: Application crash when trying to save (and fetch) a Model with unique attribute a second time
The context is to create a model instance in SwitfData and return it. This model as a unique attribute (defined by @Attribute(.unique)). The application runs fine the first time but on the second run, it fails with EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP). What the reason behind this crash? Here is my sample application to duplicate the issue. The issue is reproducible on MacOS and iOS: import SwiftUI import SwiftData @available(iOS 17, *) @available(macOS 11, *) @Model public final class MyModel : CustomStringConvertible { @Attribute(.unique) var uuid: UUID init(uuid: UUID) throws { self.uuid = uuid } public var description: String { return self.uuid.uuidString } } @available(iOS 17, *) @available(macOS 11, *) @ModelActor public actor LocalDatabaseService { public static let shared = LocalDatabaseService() let schema = Schema([MyModel.self]) public init() { self.modelContainer = try! ModelContainer(for: self.schema) let context = ModelContext(modelContainer) self.modelExecutor = DefaultSerialModelExecutor(modelContext: context) } public func createMyModel(uuid: UUID) throws -> MyModel { let myModel = try MyModel(uuid: uuid) let modelContext = self.modelContext modelContext.insert(myModel) try modelContext.save() return myModel } } struct ContentView: View { var body: some View { Task { let id = UUID(uuidString: "9C66CA5B-D91C-480F-B02C-2D14EEB49902")! let myModel = try await LocalDatabaseService.shared.createMyModel(uuid: id) print("myModel:\(myModel)") print("DONE") } return VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") } .padding() } } #Preview { return ContentView() } Note: a workaround is to returned the fetched model instance return try self.getMyModel(uuid: uuid): func getMyModel(uuid: UUID) throws -> MyModel { let fetchDescriptor = FetchDescriptor<MyModel>(predicate: #Predicate { $0.uuid == uuid }) let serverList = try modelContext.fetch(fetchDescriptor) if !serverList.isEmpty { if let first = serverList.first { return first } } fatalError("Could not find MyModel with uuid \(uuid)") } ... but it does not explain the crash.
1
0
217
4w