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

Xcode - Verify App button is buggy. Nothing happens when I tap it and app says it's not verified.
I'm new to SwiftUI and Xcode. I built and installed an app to test on my iPhone 15 Pro. On the Apple Development screen for my profile, I tapped Verify App and a dialog pops up with a Cancel and Verify button. It also tells me my internet connection will be used to do the verification. After tapping the Verify button "Apple Development" on the top of the screen quickly flashes one time and the app is still in the Not Verified state. No error message is ever displayed. It looks like I came across a bug in Apples verification process. Please show me a detailed step by step work-around to this bug. I'm using Xcode 15.4 Thanks in advance.
1
0
202
2w
Passkey AutoFill won't show the "passkey" prompt above the native keyboard
We implemented passkeys Autofill feature in iOS 16.6. Later verified in iOS 17.0 as well. But when we upgraded to iOS 17.5, the available passkeys autofill prompt is disappeared now. No code changes were done from our side. Also upgraded to iOS 17.5.1 and checked, still doesn’t show the prompt on the keyboard. For autofill we are calling 'performAutoFillAssistedRequests()' API on our ASAuthorizationController after fetching assertion options response from our Relying-Party. Our textFields content type is set to ‘username’. Additional Info: Before making the performAutoFillAssistedRequests() API call, when we click on the ‘Passwords’ icon on keyboard, it only shows the passwords saved on iPhone. But after making the call, we can see available passkeys as well in the list. We are making the fetch assertion options response call on textField delegate after typing more than two characters. I already raised a bug in Feedback Assistant on this - FB13809196. I attached a video and sysdiag file there.
0
0
243
2w
Make my SwiftData code concurrency proof (sendable model, singleton)
Here is my current code: @Model final public class ServerModel { @Attribute(.unique) var serverUrl: URL init(serverUrl: URL) { self.serverUrl = serverUrl } } @ModelActor public actor MyDatabaseService { public static var shared = MyDatabaseService() public init() { self.modelContainer = try! ModelContainer(for: ServerModel.self) let context = ModelContext(modelContainer) self.modelExecutor = DefaultSerialModelExecutor(modelContext: context) } public func listServers() throws -> [ServerModel] { let descriptor = FetchDescriptor<ServerModel>() return try modelContext.fetch(descriptor) } } When try to call try await MyDatabaseService.shared.listServers() There are two problems: ServerModel is not Sendable "Reference to static property 'shared' is not concurrency-safe because it involves shared mutable state; this is an error in Swift 6" For the first one, I can solve it by doing: public struct Server { let serverUrl: URL; } @Model final public class ServerModel { @Attribute(.unique) var serverUrl: URL init(serverUrl: URL) { self.serverUrl = serverUrl } func getSendable() -> Server { return Server(serverUrl: self.serverUrl) } } @ModelActor public actor MyDatabaseService { (...) public func listServers() throws -> [Server] { let descriptor = FetchDescriptor<ServerModel>() return try modelContext.fetch(descriptor).map { $0.getSendable() } } } I am wondering if there is a smarter solution to this first issue. SwiftData already require to define the model with basic/codable types, so if there was a magic way to get a sendable from the model. I try to make my model 'Codable' but 'Codable' is not compatible with 'Sendable'. For my second issue, the singleton issue. I do not really know how to fix it.
1
0
172
2w
SwiftUI Trap change of orientation
The real truth is that I don't know what I am doing. I am trying to trap the change of orientation event. I have been strongly advised to use "Size Classes" rather than "Landscape" or "Portrait". Apparently, this is what Apple recommends. I have tried two or three ways to do this, and my closest effort to get it working has run me into an Issue (code below) that I don't know how to solve. I believe I have to use the @Evinroment macros to pick up the current size classes (@Environment(\.horizontalSizeClas) var .... and @Environment(\.verticalSizeClass) var ....) and these have to go inside a "View", I think. But I know when I get to setting up the Notification Center I will have to use the @Published macro to pass the orientation value back to my main "ContentView", again I think. And the @Published macro needs to run in a class. So I have tried to put a "View" inside a "class" and run into an issue that the @Pulished variable (a String) is only recognised in the "class" and the size classes are only recognised in the "View". So How do I overcome this? Here is the Code I have come up with so far, it is incomplete and when I get this working I will add more. import SwiftUI final class OrientChange { @Published public var myOrient: String init(myOrient: String){ self.myOrient = myOrient } struct SizeClassView: View { @Environment(\.horizontalSizeClass) var myHorizClass: UserInterfaceSizeClass? @Environment(\.verticalSizeClass) var myVertClass: UserInterfaceSizeClass? var body: some View { Text("Horiz Class: \(myHorizClass)") if myHorizClass == .compact && myVertClass == .regular { OrientChange.myOrient = "Portrait" } else { Text("No") } } } } #Preview { OrientChange.SizeClassView() }
2
0
248
2w
Storing Different Types of Swift Objects in C++ Using New Interop
Hello Everyone, I'm working on an app that utilizes the new C++ - Swift interop feature. I have a module called ModuleA that contains multiple Swift classes, and I need to store instances of these classes in a C++ class as a class member(to ensure ARC until the class object is deallocated). However, I want to retain the Swift class objects on the stack without directly allocating heap memory from C++. Sample Swift Code: public class SwiftClassA { public init() {} public func FuncA() -&gt; Void { // Perform operations specific to SwiftClassA } } public class SwiftClassB { public init() {} public func FuncA() -&gt; Void { // Perform operations specific to SwiftClassB } } // Additional Swift classes (SwiftClassC to SwiftClassN) follow a similar structure. Sample Cpp Code: CppClass.hpp #include "ModuleA-Swift.h" // Include generated Swift headerclass CppClass { public: // Functions and declarationsprivate: XYZ vClassObject; // Placeholder for Any Swift class object }; CppClass.cpp #include "ModuleA-Swift.h" // Include generated Swift headervoid CppClass::SomeFuncA() noexcept { ModuleA::SwiftClassA obj = ModuleA::SwiftClassA::init(); // Initialize SwiftClassA object vClassObject = obj; // Assign SwiftClassA object to vClassObject } void CppClass::SomeFuncB() noexcept { ModuleA::SwiftClassB obj = ModuleA::SwiftClassB::init(); // Initialize SwiftClassB object vClassObject = obj; // How do I Assign SwiftClassB object to vClassObject? } I'm looking for suggestions on how to efficiently store different types of Swift class objects in my C++ class while maintaining stack-based object retention and proper memory management. Any help or insights would be greatly appreciated. Thanks, Harshal
4
0
326
2w
SwiftUI Orientation Change
I have been struggling for nearly a week to handle orientation changes. In a previous post https://developer.apple.com/forums/thread/755957 I was strongly advised to use Size Classes, and I am trying to do that. by following this post: https://forums.developer.apple.com/forums/thread/126878) But I still can get it to work, so far I am just trying to initialize all the variables I will use later on. please bear with me I am 65 and have not done any coding for coming for 40 years. This my latest effort: import SwiftUI final class myOrientationChange: ObservableObject { @Published var myOrient: String = "" @Environment(\.verticalSizeClass) var myVertClass: UserInterfaceSizeClass? @Environment(\.horizontalSizeClass) var myHorizClass: UserInterfaceSizeClass? var _observer: NSObjectProtocol? if myHorizClass == .compact && myVertClass == .regular { self.myOrient = "Portrait" } elseif myHorizClass == .regular && myVertClass == .compact { self.myOrient = "Landscape" } else { self.myOrient = "Something Else" } } struct ContentView: View { @EnvironmentObject var envOrient: myOrientationChange var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") Text("Orientation is \(envOrient.myOrient)") } .padding() } } #Preview { ContentView() } I will go on to use the NotificationCenter to trap there change of orientation even. On the line if myHorizClass == ......... It tells me "Expected declaration in declaration of 'myOrientChange'" What have I done wrong?
1
0
231
3w
SwiftData does not retrieve my inverse one-to-many Relationship
Here is my models: import SwiftData @Model final public class FirstModel { let name: String @Relationship(deleteRule: .cascade, inverse: \SecondModel.parent) var children = [SecondModel]() init(name: String) { self.name = name } } @Model final public class SecondModel { let parent: FirstModel let name: String @Relationship(deleteRule: .cascade, inverse: \ThirdModel.parent) var children = [ThirdModel]() init(name: String, parent: FirstModel) { self.name = name self.parent = parent } } @Model final public class ThirdModel { let parent: SecondModel let name: String init(name: String, parent: SecondModel) { self.name = name self.parent = parent } } Then I create my model entries: let schema = Schema([ FirstModel.self, SecondModel.self, ThirdModel.self ]) let container = try ModelContainer(for: schema) let context = ModelContext(container) let firstModel = FirstModel(name: "my first model") let secondModel = SecondModel(name: "my second model", parent: firstModel) let thirdModel = ThirdModel(name: "my third model", parent: secondModel) context.insert(firstModel) context.insert(secondModel) context.insert(thirdModel) try context.save() I want to retrieve the children from my models: print("-- Fetch Third Model") let thirdFetchDescriptor: FetchDescriptor<ThirdModel> = FetchDescriptor<ThirdModel>(predicate: #Predicate { $0.name == "my third model" }) let thirdModels = try context.fetch(thirdFetchDescriptor) for entry in thirdModels { print(">>> \(entry) - \(entry.parent) - \(entry.parent.parent)") } print("-- Fetch First Model") let firstFetchDescriptor: FetchDescriptor<FirstModel> = FetchDescriptor<FirstModel>(predicate: #Predicate { $0.name == "my first model" }) let firstModels = try context.fetch(firstFetchDescriptor) for entry in firstModels { print(">>> \(entry) - \(entry.children)") for child in entry.children { print("\t>>> \(child) - \(child.children)") } } ... But it does not seem to work: -- Fetch Third Model >>> cardapart_sdk_app_ui.ThirdModel - cardapart_sdk_app_ui.SecondModel - cardapart_sdk_app_ui.FirstModel -- Fetch First Model >>> cardapart_sdk_app_ui.FirstModel - [] What I would expect to see: -- Fetch First Model >>> cardapart_sdk_app_ui.FirstModel - [cardapart_sdk_app_ui.SecondModel] >>> cardapart_sdk_app_ui.SecondModel - [cardapart_sdk_app_ui.ThirdModel] I am not sure what I am doing wrong or missing...
1
0
264
3w
(Swift) TextField border contained in a view remains visible even when the view is fully overlapped by another view.
I have a ZStack that contains a VStack with 2 views (view1 and view2) and a third view (view3). So, is either that view1 and View1 are visible, or view3 is visible. This is the relevant code: ZStack { VStack { view1() View2() } if showView3 View3() } view1 and view2 are 400px in width and 200px in height, while view3 is 400 x 400 px, so that it completely overwrite view1/view2 when visible. The problem I'm trying to solve is that the border of a TextField placed in view1 is visible when showView3 is true, what should not be happening (possible glitch in swift?). To show the problem, I prepared a code sample, which shows that when view3 is active, it completely overwrites view1/view2, but still, the border of the TextField remains visible. (See screenshot below) struct TestZStackView: View { @State private var showView3 = false var body: some View { ZStack { VStack { Toggle("view3", isOn: $showView3) View1() .frame(width: 400, height: 200) .background(Color.red) .zIndex(1) View2() .frame(width: 400, height: 200) .background(Color.green) .zIndex(1) } if showView3 { View3() .frame(width: 400, height: 400) .background(Color.blue) .zIndex(2) } } } } struct View1: View { var body: some View { TextField("Enter text", text: .constant("")) .padding() .cornerRadius(5) .textFieldStyle(RoundedBorderTextFieldStyle()) .zIndex(1) } } struct View2: View { var body: some View { Color.clear } } struct View3: View { var body: some View { Color.black // (Ensure no transparency) } } zIndex() are not required, I just placed them to see if the problem get solved, but it may no difference. BTW, in the code above, the visible border disappears if the view is minimized, but that is not the case in the real app I'm working on. In the screenshots attached, it can be seen how the TextField border remains visible when view3 is active ("https://developer.apple.com/forums/content/attachment/d0e75f25-d36e-4361-af64-54252d1f2a98" "title=Screenshot 2024-05-24 at 10.06.03 PM.png;width=800;height=632")
0
0
199
3w
(Swift) TextField border contained in a view remains visible even when the view is fully overlapped by another view.
I have a ZStack that contains a VStack with 2 views (view1 and view2) and a third view (view3). So, is either that view1 and View1 are visible, or view3 is visible. This is the relevant code: ZStack { VStack { view1() View2() } if showView3 View3() } view1 and view2 are 400px in width and 200px in height, while view3 is 400 x 400 px, so that it completely overwrite view1/view2 when visible. The problem I'm trying to solve is that the border of a TextField placed in view1 is visible when showView3 is true, what should not be happening (possible glitch in swift?). To show the problem, I prepared a code sample, which shows that when view3 is active, it completely overwrites view1/view2, but still, the border of the TextField remains visible. (See screenshot below) struct TestZStackView: View { @State private var showView3 = false var body: some View { ZStack { VStack { Toggle("view3", isOn: $showView3) View1() .frame(width: 400, height: 200) .background(Color.red) .zIndex(1) View2() .frame(width: 400, height: 200) .background(Color.green) .zIndex(1) } if showView3 { View3() .frame(width: 400, height: 400) .background(Color.blue) .zIndex(2) } } } } struct View1: View { var body: some View { TextField("Enter text", text: .constant("")) .padding() .cornerRadius(5) .textFieldStyle(RoundedBorderTextFieldStyle()) .zIndex(1) } } struct View2: View { var body: some View { Color.clear } } struct View3: View { var body: some View { Color.black // (Ensure no transparency) } } zIndex() are not required, I just placed them to see if the problem get solved, but it may no difference. BTW, in the code above, the visible border disappears if the view is minimized, but that is not the case in the real app I'm working on. In the screenshots attached, it can be seen how the TextField border remains visible when view3 is active ("https://developer.apple.com/forums/content/attachment/d0e75f25-d36e-4361-af64-54252d1f2a98" "title=Screenshot 2024-05-24 at 10.06.03 PM.png;width=800;height=632")
0
0
189
3w
Get user's own contact card with unifiedMeContactWithKeys(toFetch:)
Hi everyone! It came to my knowledge from the documentation (https://developer.apple.com/documentation/contacts/cncontactstore/unifiedmecontactwithkeys%28tofetch:%29) that the method unifiedMeContactWithKeys(toFetch:), which fetches the me-card in the phone book by using CNContactStore, was recently made available for iOS as well. The problem is that I regardless get the error saying the method is unavailable for iOS, even though the documentation clearly states it should be available. I have tried several Xcode version including the latest one but to no avail... Does anyone have any idea what is wrong here? Kindest regards, Andreas
1
0
341
3w
Swift: Declaration name is not covered by macro
Hello! I'm trying to generate a protocol dependent for another one using Swift macros. The implementation looks like the following: @attached (peer, names: suffixed (Dependent),prefixed (svc)) public macro dependableService() = #externalMacro (module: "Macros", type: "DependableServiceMacro") public struct DependableServiceMacro: PeerMacro { public static func expansion (of node: AttributeSyntax, providingPeersOf declaration: some DeclSyntaxProtocol, in context: some MacroExpansionContext) throws -> [DeclSyntax] { guard let baseProto = declaration.as (ExtensionDeclSyntax.self) else { return [] } let nm = baseProto.extendedType.trimmedDescription let protoNm = nm + "Dependent" let varNm = "svc" + nm let protoDecl: DeclSyntax = """ protocol \(raw: protoNm) : ServiceDependent { var \(raw: varNm) : \(raw: nm) { get set } } """ return [protoDecl] } } When I try using it in my code like this @dependableService extension MyService {} the macro correctly expands to the following text: protocol MyServiceDependent : ServiceDependent { var svcMyService : MyService { get set } } However, the compiler gives me the error: error: declaration name 'MyServiceDependent' is not covered by macro 'dependableService' protocol MyServiceDependent : ServiceDependent { ^ Do I understand correctly, that for some reason the compiler cannot deduce the name of the generated protocol based on the name of the extensible protocol, despite the presence of the names: suffixed(Dependent) attribute in the macro declaration? Could anybody please tell me what I'm doing wrong here? Thanks in advance
1
0
242
3w
Increase in app crashes on iOS 17.4
We have an iOS app built using Capacitor. We are seeing a large increase in app crashes on iOS 17.4 (iPhone). Other OS versions seem to be showing significantly fewer crash numbers. We are unsure what is causing this, as our app did not go through any major releases. I have attached the crash log below. Thanks Exception Type: EXC_CRASH (SIGKILL) Exception Codes: 0x0000000000000000, 0x0000000000000000 Termination Reason: RUNNINGBOARD 0xd00d2bad
5
0
431
3w
How to get selected usdz model thumbnail image using QuickLookThumbnailing
I am doing below code for getting thumbnail from usdz model using the QuickLookThumbnailing, But don't get the proper out. guard let url = Bundle.main.url(forResource: resource, withExtension: withExtension) else{ print("Unable to create url for resource.") return } let request = QLThumbnailGenerator.Request(fileAt: url, size: size, scale: 10.0, representationTypes: .all) let generator = QLThumbnailGenerator.shared generator.generateRepresentations(for: request) { thumbnail, type, error in DispatchQueue.main.async { if thumbnail == nil || error != nil { print(error) }else{ let tempImage = Image(uiImage: thumbnail!.uiImage) print(tempImage) self.thumbnailImage = Image(uiImage: thumbnail!.uiImage) print("=============") } } } } Below Screen Shot for selected model : Below is the thumbnail image, which not come with guitar but get only usdz icon.
1
0
218
3w
Apple activity ring(sparkle)
Hello everyone My goal is to create Apple's activity ring sparkle effect. So I found Paul Hudson's Vortex library. There is already a sparkle effect, but I don't know how to modify it to achieve my goal. Because I'm pretty new to SwiftUI animations. Does anyone have any idea how I could do this? Vortex project: https://github.com/twostraws/Vortex
2
0
271
3w
Problem with NavigationStack(path:)
Hello everyone. I am developing an application with SwiftUI. I am having trouble with NavigationStack(path: ). 1st problem: After the application runs, after clicking on the first list item, there is a flicker in the title section. I think it is the .navigationDestination that causes this problem, because when I change the navigationLink to Button in the “ActiveRegQueryView” screen, this problem disappears. 2nd Problem: When you click on a list item, sometimes it stays pressed (grayed out) and does not take you to the screen (Video 1). If you try to click on an item more than once, navigatinLink passes more than one value to path and opens more than one page (I noticed this with path.count) (Video 2). I don't have this problem if you edit the back button on the screen it takes you to (ActiveRegDetailView). (vm.path.removeLast()) The reason I use path is to close multiple screens and return to the start screen. Video 1: Video 2: Main View: import SwiftUI struct ActiveRegView: View { @Environment(NavigationViewModel.self) private var navViewModel @AppStorage("sortOption") private var sortOrder: sorting = .byBrand @State private var searchText = "" var body: some View { @Bindable var navViewModel = navViewModel NavigationStack(path: $navViewModel.path) { // <- if i don't use path everything is OK List { ActiveRegQueryView(searchText: searchText, sortOrder: sortOrder) // <- Dynamic Query View } .navigationDestination(for: Registration.self, destination: { ActiveRegDetailView(reg: $0) .toolbar(.hidden, for: .tabBar) }) } } } Dynamic Query View: import SwiftData import SwiftUI struct ActiveRegQueryView: View { @Query private var regs: [Registration] @Environment(NavigationViewModel.self) var vm init(searchText: String, sortOrder: sorting) { var order: SortDescriptor<Registration> switch sortOrder { case .byBrand: order = SortDescriptor(\.brand) case .byDateDescending: order = SortDescriptor(\.entryRegistration.entryDate, order: .reverse) case .byDateAscending: order = SortDescriptor(\.entryRegistration.entryDate) } _regs = Query(filter: #Predicate { if !searchText.isEmpty { if $0.activeRegistration && ($0.brand.localizedStandardContains(searchText) || $0.model.localizedStandardContains(searchText) || $0.plate.localizedStandardContains(searchText)) { return true } else { return false } } else { return $0.activeRegistration } }, sort: [order]) } var body: some View { ForEach(regs) { reg in NavigationLink(value: reg) { ListRowView(reg: reg) } // Button { // vm.path.append(reg) // } label: { // ListRowView(reg: reg) // } // .buttonStyle(.plain) } } } I look forward to your ideas for solutions. Thank you for your time.
0
0
186
3w
SwiftUI: How do I tell when my device orientation changes
Sorry to repeat this, but the new style forum won't allow me access to the original version of this question, and the answers. I have been searching the internet for 3 or 4 days now to find only complex solutions that I cannot get working. All I want to do is determine when the device orientation changes so that I can update the background Image. This is what I have so far: Import SwiftUI struct Main_Menu_iPhone: View { @State private var bloodGlucose: Float = 0.0 var body: some View { ZStack { Image("iPhone Background Portrait 828 x 1792 ") .resizable() .aspectRatio(contentMode: .fill) VStack { HStack { Label("Blood Glucose", systemImage: "drop.fill") TextField("Blood Glucose : ", value: $bloodGlucose, format: .number) .onSubmit() { print("Your Blood Gluse is : \(bloodGlucose)") } .background(.white) .frame(alignment: .topTrailing) Spacer() } Spacer() }.padding(.top, 250) } } }
1
0
345
3w
SwiftUI: How do I detect a change in device orientation?
Please can someone help I have spent 3 - 4 days trawling the internet and only finding complex answers that I can't get to work, and my head is ready to explode. I only want to detect when the device orientation has changed and load a different background image. This is what I have so far: import SwiftUI struct Main_Menu_iPhone: View { @State private var bloodGlucose: String = "0.0" var body: some View { ZStack { Image("iPhone Background Portrait 828 x 1792 ") .resizable() .aspectRatio(contentMode: .fill) VStack { TextField("Blood Glucose : ", text: $bloodGlucose) Spacer() } } } } #Preview { Main_Menu_iPhone() }
2
0
276
3w
Game Center fetchSavedGames sometimes returns empty list of games, although it works correctly on the next tries
I have implemented the Game Center for authentication and saving player's game data. Both authentication and saving player's data works correctly all the time, but there is a problem with fetching and loading the data. The game works like this: At the startup, I start the authentication After the player successfully logs in, I start loading the player's data by calling fetchSavedGames method If a game data exists for the player, I receive a list of SavedGame object containing the player's data The problem is that after I uninstall the game and install it again, sometimes the SavedGame list is empty(step 3). But if I don't uninstall the game and reopen the game, this process works fine. Here's the complete code of Game Center implementation: class GameCenterHandler { public func signIn() { GKLocalPlayer.local.authenticateHandler = { viewController, error in if let viewController = viewController { viewController.present(viewController, animated: false) return } if error != nil { // Player could not be authenticated. // Disable Game Center in the game. return } // Auth successfull self.load(filename: "TestFileName") } } public func save(filename: String, data: String) { if GKLocalPlayer.local.isAuthenticated { GKLocalPlayer.local.saveGameData(Data(data.utf8), withName: filename) { savedGame, error in if savedGame != nil { // Data saved successfully } if error != nil { // Error in saving game data! } } } else { // Error in saving game data! User is not authenticated" } } public func load(filename: String) { if GKLocalPlayer.local.isAuthenticated { GKLocalPlayer.local.fetchSavedGames { games, error in if let game = games?.first(where: {$0.name == filename}){ game.loadData { data, error in if data != nil { // Data loaded successfully } if error != nil { // Error in loading game data! } } } else { // Error in loading game data! Filename not found } } } else { // Error in loading game data! User is not authenticated } } } I have also added Game Center and iCloud capabilities in xcode. Also in the iCloud section, I selected the iCloud Documents and added a container. I found a simillar question here but it doesn't make things clearer.
0
0
181
3w
Weird Swift overriding cocoapods
I don't even use Swift. I use Flutter. I am getting this odd always_embed_swift library warning that seems to be overriding my runner target on xcode. I'll just attach the image down below of what I'm dealing with. Please an apple engineer or someone just help me because this has been a struggle lol. I need to change this but can't find the setting to do so.
0
0
177
3w