Swift is a powerful and intuitive programming language for Apple platforms and beyond.

Swift Documentation

Posts under Swift tag

2,036 Posts
Sort by:
Post not yet marked as solved
0 Replies
2 Views
Hello together, i want to us some classes to manage informations, which get fetched from a firestore database. My idea was, that I will have different classes for the different state of informations. The information which will be common for the different states should have the same properties. Therefore it made sense for me to have a super class which stores the main informations and derive a subclass with extra properties to store the more informations. My question is, how to define the initializer method properly, so that I can store these data informations fetched from firestore at once without any loss. Superclass (I reduced it to a minimum, just to show my principal problem): class GameInfo: Codable, Identifiable { @DocumentID var id: String? // -> UUID of firestore document var league: String var homeTeam: String var guestTeam: String enum CodingKeys: String, CodingKey { case league case homeTeam case guestTeam } init(league: String, homeTeam: String, guestTeam: String) { self.league = league self.homeTeam = homeTeam self.guestTeam = guestTeam } } the subclass should contain the GameInfo Properties and some others ... class Game: GameInfo { var startTime: Date? enum CodingKeys: String, CodingKey { case startTime } init(league: String, homeTeam: String, guestTeam: String, startTime: Date) { self.startTime = startTime super.init(league: league, homeTeam: homeTeam, guestTeam: guestTeam) } required init(from decoder: any Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.startTime = try values.decodeIfPresent(Date.self, forKey: .startTime) super.init(league: "", homeTeam: "",, guestTeam: "") } With the required init-method, informations get decoded and stored. (the data from firestore contain the league, homeTeam, guestTeam and startTime informations). The super.init() method as defined results in empty strings. But what I want is, that the league, homeTeam and guestTeam values will also be decoded from the firestore informations. But I don't know how. If I use the code super.init(league: league, homeTeam: homeTeam, guestTeam: guestTeam) within the required init() than I get the compiler error message 'self' used in property access 'league' before 'super.init' call What is wrong in my thinking ? Any help appreciated. Thanks and best regards Peter
Posted
by Luggi71.
Last updated
.
Post not yet marked as solved
1 Replies
43 Views
We've been working on a SwiftUI app that randomly crashes with an exception. When navigating from one view to another, a rare exception is thrown, maybe every 1 / 200 times or so: <SwiftUI.UIKitNavigationController: 0x109888400> is pushing the same view controller instance (<_TtGC7SwiftUI32NavigationStackHostingControllerVS_7AnyView_: 0x10792d400>) more than once which is not supported and is most likely an error in the application : com.<companyName>.<appName> We haven't coded anything to directly push an instance of a view controller outside of what SwiftUI is doing. It seems to happen when the user taps on a NavigationLink view. It happens both in simulator and on device. Does anyone know what might cause this?
Posted
by GBecker.
Last updated
.
Post not yet marked as solved
0 Replies
26 Views
Hi We getting error in Apple Sign In "Sign-Up not completed", Apple sign in working fine for old Apps and old Bundle ids, But it's not working in new Apps and new Bundle ids We checked with other Apple Developer team accounts Apple Sign In is working on the same source code. But my Team account is getting an error. We enabled signing capabilities and added Sign in with Apple and we added Provisioning profile certificate also , but I am still getting the same error.
Posted Last updated
.
Post not yet marked as solved
0 Replies
22 Views
Hi, I'm trying to build an app to connect to both BR/EDR ("Classic") or BLE devices. For Classic, the recommended flow in Apple docs is: Start your app and initialize your CBCentralManager Pair the phone and the device manually through settings This should automatically call the connectionEventDidOccur From then on it depends on the dev to choose what to do with the information from the callback (peripheral, event, etc), but the callback is simply never fired. Here's my basic implementation of the callback: func centralManager(_ central: CBCentralManager, connectionEventDidOccur event: CBConnectionEvent, for peripheral: CBPeripheral) { print("IOS: connectionEventDidOccur for peripheral: %@", peripheral) if (event == .peerConnected) { print("IOS: Case is peer connected") connectToPeripheral(peripheral.identifier.uuidString) if(!savedPeripheralList.contains(where: { $0.identifier == peripheral.identifier })){ savedPeripheralList.append(peripheral) } } else if (event == .peerDisconnected ){ print("IOS: Peer %@ disconnected!", peripheral) } else { print("IOS: if statement didn't work") } } I'm essentially: Printing the fact that the callback was called Trying to connect the app to the peripheral (by now only the phone is connected) Saving this newly connected peripheral to a local list For context, I've been able to scan and connect to BLE devices like earbuds normally, so my general implementation of other callbacks like didDiscover or didConnect works just fine, this is the only non functional callback. Any ideas would be appreciated, thanks!
Posted Last updated
.
Post not yet marked as solved
0 Replies
17 Views
The regular case. Open a sheet by clicking a button. Next close the sheet using a Cancel button on it. The isPresented state variable is changed immediately, but while the dismissing animation isn't totally finished it's impossible to click the Button on the main parent screen and call the sheet presentation again. As I understand UIKit works differently and lets us click the Button but just calls a new modal view exactly after the previous animation is finished struct MyView: View { @State private var isPresented = false public var body: some View { VStack { Button(action: { isPresented = true }, label: { Text("Button") }) Spacer() } .sheet(isPresented: $isPresented) { sheetContent } } var sheetContent: some View { VStack { Text("Cancel") .onTapGesture { isPresented = false } Spacer() } } } @Apple Could you please fix it in SwiftUI?
Posted Last updated
.
Post not yet marked as solved
0 Replies
14 Views
Condition: We have an existing app that runs on iPhone and iPad. We want to make it compatible with macOS, along with it we want to leverage some of the macOS native components. We achieved this using macCatalyst, but now we want to build common components using swiftUI for both macOS and iOS platforms. Challenge: Using SwiftUI view for mac development Approach 1: We created a Mac bundle that contained Mac specific views (using Appkit views). This approach worked fine for creating and using components that are specific to macOS. Now while developing and using SwiftUI views in mac bundle we face following error -> (NSHostingViewController symbol not found). Approach 2: We tried creating a separate Mac app and make it part of MacCatalyst app. In this approach we were able to show NSStatusBar and add text using SwiftUI view. But the status bar appearance is inconsistent, sometimes NSStatusBar icon appears but other times it just won't appear. Can anyone help with the right approach for this scenarios
Posted Last updated
.
Post not yet marked as solved
2 Replies
103 Views
Hello, I'm looking for a way to detect using NWPathMonitor when the iOS device is connected to a router but not to the internet. As an example a mobile router WiFi without SIM. In settings I'm able to switch the connection to its WiFi, once connected a label below the SSID shows Not connected to the internet. I would like to show the same thing to the user inside my app, but unfortunately I always get the satisfied answer. Am I missing something in configuring NWPathMonitor or reading the answer? final class InternetConnectionMonitor { lazy var internetConnectionStatusPublisher: AnyPublisher&lt;InternetConnectionStatus, Never&gt; = { _internetConnectionStatusSubject .compactMap{ $0 } .eraseToAnyPublisher() }() var lastInternetConnectionStatus: InternetConnectionStatus? { _internetConnectionStatusSubject.value } private let _internetConnectionStatusSubject = CurrentValueSubject&lt;InternetConnectionStatus?, Never&gt;(nil) private let pathMonitor = NWPathMonitor() private let pathMonitorQueue = DispatchQueue(label: "com.xxxxx-network-monitor", qos: .default) init() { startPathMonitoring() } private func startPathMonitoring() { pathMonitor.pathUpdateHandler = { [weak self] path in guard let self else { return } let networkStatus = InternetConnectionStatus(from: path) self._internetConnectionStatusSubject.send(networkStatus) } pathMonitor.start(queue: pathMonitorQueue) } }
Posted
by DrAma78.
Last updated
.
Post not yet marked as solved
1 Replies
79 Views
I prepare an app to migrate from ObservableObject to Observable, from EnvironmentObject to Environment(MyClass.self) and so so forth. That works OK, very simple. But, that forces to run on macOS 14 or more recent. So I would like to have it conditionally, such as: if macOS 14 available @Environment(ActiveConfiguration.self) var activeConfiguration: ActiveConfiguration otherwise @EnvironmentObject var activeConfiguration: ActiveConfiguration The same for the class declaration: if macOS 14 available @Observable class ActiveConfiguration { var config = Configuration() } otherwise class ActiveConfiguration : ObservableObject { @Published var config = Configuration() } Is there a way to achieve this (I understand it is not possible through extensions of Macros, as we can do for modifiers) ? Could I define 2 classes for ActiveConfiguration, but then what about @Environment ?
Posted
by Claude31.
Last updated
.
Post not yet marked as solved
2 Replies
93 Views
On my shop and content views of my app, I have a shopping cart SF symbol that I've modified with a conditional to show the number of items in the cart if the number of items is above zero. However, whenever I change tabs and back again, that icon disappears even though there should be an item in the cart. I have a video of the error, but I have no idea how to post it. Here is some of the code, let me know if you need to see more of it: CartManager.swift import Foundation import SwiftUI @Observable class CartManager { /*private(set)*/ var products: [Product] = [] private(set) var total: Int = 0 private(set) var numberofproducts: Int = 0 func count() -> Int { numberofproducts = products.count return numberofproducts } func addToCart(product: Product) { products.append(product) total += product.price numberofproducts = products.count } func removeFromCart(product: Product) { products = products.filter { $0.id != product.id } total -= product.price numberofproducts = products.count } } ShopPage.swift import SwiftUI struct ShopPage: View { @Environment(CartManager.self) private var cartManager var columns = [GridItem(.adaptive(minimum: 135), spacing: 0)] @State private var searchText = "" let items = ["LazyHeadphoneBean", "ProperBean", "BabyBean", "RoyalBean", "SpringBean", "beanbunny", "CapBean"] var filteredItems: [Bean] { guard searchText.isEmpty else { return beans } return beans.filter { $0.imageName.localizedCaseInsensitiveContains(searchText) } } var body: some View { NavigationStack { ZStack(alignment: .top) { Color.white .ignoresSafeArea(edges: .all) VStack { AppBar() .environment(cartManager) ScrollView() { LazyVGrid(columns: columns, spacing: 20) { ForEach(productList, id: \.id) { product in NavigationLink { beanDetail(product: product) .environment(cartManager) } label: { ProductCardView(product: product) .environment(cartManager) } } } } } .navigationBarDrawer(displayMode: .always)) } } .environment(cartManager) } var searchResults: [String] { if searchText.isEmpty { return items } else { return items.filter { $0.contains(searchText)} } } } #Preview { ShopPage() .environment(CartManager()) } struct AppBar: View { @Environment(CartManager.self) private var cartManager var body: some View { NavigationStack { VStack (alignment: .leading){ HStack { Spacer() NavigationLink(destination: CartView() .environment(cartManager) ) { CartButton(numberOfProducts: cartManager.products.count) } } Text("Shop for Beans") .font(.largeTitle .bold()) } } .padding() .environment(CartManager()) } } CartButton.swift import SwiftUI struct CartButton: View { var numberOfProducts: Int var body: some View { ZStack(alignment: .topTrailing) { Image(systemName: "cart.fill") .foregroundStyle(.black) .padding(5) if numberOfProducts > 0 { Text("\(numberOfProducts)") .font(.caption2).bold() .foregroundStyle(.white) .frame(width: 15, height: 15) .background(Color(hue: 1.0, saturation: 0.89, brightness: 0.835)) .clipShape(RoundedRectangle(cornerRadius: 50)) } } } } #Preview { CartButton(/*numberOfProducts: 1*/numberOfProducts: 1) }
Posted
by KittyCat.
Last updated
.
Post not yet marked as solved
0 Replies
66 Views
Hello. I have the following question. I call the nextBatch() method on MusicItemCollection to get the next collection of artist albums. Here is my method: func allAlbums2(artist: Artist) async throws -> [Album] { var allAlbums: [Album] = [] artist.albums?.forEach { allAlbums.append($0) } guard let albums = artist.albums else { return [] } var albumsCollection = albums while albumsCollection.hasNextBatch { let response = try await albumsCollection.nextBatch() if let response { albumsCollection = response var albums = [Album]() albumsCollection.forEach({ albums.append($0)}) allAlbums.append(contentsOf: albums) } } return allAlbums } The problem is as follows. Sometimes it happens that some albums not in nextBatch are not returned (I noticed one, I didn't check the others). This happens once every 50-100 requests. The number of batches is returned the same when the album is skipped. The same albums are returned in the batch where the album was missed. I have a question, do I have a problem with multi-threading or something else or is it a problem in the API. The file contains prints of the returned batches. One with a missing album, the other without a missing one. There are about 3000 lines in the file. I will be grateful for a hint or an answer. Thank you! Here link to file: https://files.fm/u/nj4r5wgyg3
Posted
by 20a.
Last updated
.
Post not yet marked as solved
0 Replies
56 Views
I got this SSML from w3. org. AVSpeechUtterance(ssmlRepresentation:) is not complying with the contour. It doesn't change hz. <?xml version="1.0"?> <speak version="1.1" xmlns="http://www.w3.org/2001/10/synthesis" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/10/synthesis http://www.w3.org/TR/speech-synthesis11/synthesis.xsd" xml:lang="en-US"> <prosody contour="(0%,+20Hz) (10%,+30%) (40%,+10Hz)"> good morning </prosody> </speak> override func viewDidLoad() { super.viewDidLoad() guard let localUtterance = AVSpeechUtterance(ssmlRepresentation: self.speechSML) else { print("SML did not work.") return } self.utterance = localUtterance self.utterance.voice = self.voiceNoelle } self.synthesizer.speak(self.utterance)
Posted Last updated
.
Post not yet marked as solved
0 Replies
95 Views
I have been trying to enable in app purchase in sandbox environment but instead it keeps performing transactions in Xcode. Also Apple says in its docs to set up sandbox tester account in Settings &gt; App store without signing out from the non sandbox account, and says the sign in will appear as soon as we perform a transaction on device, but it does not worked for me I have ensured and tried following things: Created sand box tester id Storekit configured , all the plans fetched Has development team Tried signing in Sandbox account Checked whether I am testing in production or development build by if else (It was in development) Tested on real device Please help me get through this
Posted Last updated
.
Post not yet marked as solved
3 Replies
76 Views
Hi everyone ... i am pretty new to IOS dev, so any help would be great. I am trying to send a string "apple" from UIviewcontroller one to the UIviewcontroller sixth. I am able send the string "apple" from one UIviewcontroller to the next. But then i will have to repeat it again and again in all the views. Is there anyway i can send it directly to the sixth UIviewcontroller ?
Posted
by sonam93.
Last updated
.
Post not yet marked as solved
0 Replies
58 Views
Hello, I have a custom iOS app that takes a picture every second and uploads them to an S3 bucket. However, I was wondering if there is a way to send these images to a Mac instead via USB. Basically the app would capture a photo and send it directly to a location in Mac via USB. I couldn't find any good info online so I am not sure how realistic this is. Thanks a lot!
Posted
by gonn94.
Last updated
.
Post marked as solved
2 Replies
121 Views
Howdy, I have a ***** feeling that the answer to my question is "Y'all cain't do that!", but I figure I'll ask, anyway. THE SAD STORY (GET YOUR HANKY): We have an app that implements Sign [up|in] with Apple. It does it pretty well, with no password visible to the user, and a pretty smooth UX. The issue is what happens when users bork their install. We don't think it will happen often, but want to be able to give the user the best way out, if possible. With the regular (non-SiiA) method, they bonk on a "Forgot Password" button, and the app sends them a new password. We can't do that, with SiiA. The password is stored in the app (in the keychain, so it's very persistent, and shared across devices), and it would a Very Bad Security Hole, to allow users to simply send a new password to the server (the other method generates a rando in the server), which is what would happen, with our method of handling the password. It would also be equally bad, if the server could simply send a new password to the user, directly to their device (the other method sends an email, based on the sign-in information on the server). So the user needs to delete their keychain data completely, which we can easily do, but that does not deal with their SiiA stuff, stored on Apple's server. This is what Apple tells us to do, to delete that. WHICH BEGS THE QUESTION: My question is: Is there a URL scheme that I can use to directly open that panel? If so, it would allow us to create a screen that helps the user to do all the deletions (on the device, our server, and the Apple server).
Posted Last updated
.
Post not yet marked as solved
3 Replies
138 Views
Currently I am trying to create some shortcuts for my iOS 17 app. The AppIntent looks like this: class PostClass{ public init() { let url = URL(string: "http://myurl")! var request = URLRequest(url: url) request.httpMethod = "POST" struct Message: Encodable { let device_type: String } let message = Message( device_type: "device" ) let data = try! JSONEncoder().encode(message) request.httpBody = data request.setValue( "application/json", forHTTPHeaderField: "Content-Type" ) self.request = request } } var activateDevice = PostClass() @available(iOS 17, *) struct ActivateIntent: AppIntent { static let title: LocalizedStringResource = "Activate" func perform() async throws -> some IntentResult { let task = URLSession.shared.dataTask(with: activateDevice.request) { data, response, error in let statusCode = (response as! HTTPURLResponse).statusCode if statusCode == 200 { print("SUCCESS") } else { print("FAILURE") } } task.resume() return .result() } } Unfortunately, the shortcut throws an error after every second execution. I looked into the ips-file and saw the following traceback: Thread 2 Crashed: 0 Runner 0x1028ddd30 closure #1 in ActivateIntent.perform() + 388 1 CFNetwork 0x1a6f39248 0x1a6f2a000 + 62024 2 CFNetwork 0x1a6f57210 0x1a6f2a000 + 184848 3 libdispatch.dylib 0x1adced13c _dispatch_call_block_and_release + 32 4 libdispatch.dylib 0x1adceedd4 _dispatch_client_callout + 20 5 libdispatch.dylib 0x1adcf6400 _dispatch_lane_serial_drain + 748 6 libdispatch.dylib 0x1adcf6f64 _dispatch_lane_invoke + 432 7 libdispatch.dylib 0x1add01cb4 _dispatch_root_queue_drain_deferred_wlh + 288 8 libdispatch.dylib 0x1add01528 _dispatch_workloop_worker_thread + 404 9 libsystem_pthread.dylib 0x201dd4f20 _pthread_wqthread + 288 10 libsystem_pthread.dylib 0x201dd4fc0 start_wqthread + 8 Is there any way to locate the error with these information? Has it something to do with the fact that my code is not thread-safe? Or is there any internal bug? Grateful for any help, thanks in advance!
Posted
by alex_hsv.
Last updated
.
Post not yet marked as solved
0 Replies
105 Views
I created a standalone iMessage app using Xcode template as the below: I didn't change a single line of code except just populating all necessary icons. After installing the extension using Xcode, nothing showed up in the iMessage. Did I miss anything? I've been stuck here for many hours.
Posted
by bfiodev.
Last updated
.
Post not yet marked as solved
0 Replies
168 Views
Hey, i just created and trained an MLImageClassifier via the MLImageclassifier.train() method (https://developer.apple.com/documentation/createml/mlimageclassifier/train(trainingdata:parameters:sessionparameters:)) For my Trainingdata (MLImageclassifier.DataSource) i am using my directoy structure, so i got an images folder with subfolders of person1, person2, person3 etc. which contain images of the labeled persons (https://developer.apple.com/documentation/createml/mlimageclassifier/datasource/labeleddirectories(at:)) I am saving the checkpoints and sessions in my appdirectory, so i can create an MLIMageClassifier from an exisiting MLSession and/or MLCheckpoint. My question is: is there any way to add new labels, optimally from my directoy strucutre, to an MLImageClassifier which i create from an existing MLCheckpoint/MLSession? So like adding a person4 and training my pretrained Classifier with only that person4. Or is it simply not possible and i have to train from the beginning everytime i want to add a new label? Unfortunately i cannot find anything in the API. Thanks!
Posted Last updated
.
Post not yet marked as solved
0 Replies
129 Views
In my SwiftUI view, I try to load the image from data. var body: some View { Group{ if let data = model.detailImageData, let uiimage = UIImage(data: data) {// no memory issue Image(uiImage: uiimage) .resizable() .scaledToFit() } } } But I want to get the HDR style of my image, so I use if let data = model.detailImageData, let uiimage = UIImageReader.default.image(data:data){ //memory leaks!!! When I change the data, the memory of the previous image is never freeed. finally caused my app to crash. You can see it from the Instrument screenshot.
Posted
by SpaceGrey.
Last updated
.