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

Swift Documentation

Posts under Swift tag

2,030 Posts
Sort by:
Post not yet marked as solved
0 Replies
5 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
2 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
7 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
5 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
96 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<InternetConnectionStatus, Never> = { _internetConnectionStatusSubject .compactMap{ $0 } .eraseToAnyPublisher() }() var lastInternetConnectionStatus: InternetConnectionStatus? { _internetConnectionStatusSubject.value } private let _internetConnectionStatusSubject = CurrentValueSubject<InternetConnectionStatus?, Never>(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
68 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
80 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
58 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
49 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
88 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
71 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
54 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
118 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
135 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
97 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
162 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
127 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
.
Post not yet marked as solved
0 Replies
115 Views
I use this code to show the Image in HDR in SwiftUI struct HDRImageView: UIViewRepresentable { // Set up a common reader for all UIImage read requests. static let reader: UIImageReader = { var config = UIImageReader.Configuration() config.prefersHighDynamicRange = true return UIImageReader(configuration: config) }() let data:Data? let enableHDR:Bool func makeUIView(context: Context) -> UIImageView { let view = UIImageView() view.preferredImageDynamicRange = enableHDR ? .high : .standard update(view) // Set this view to fit itself to the parent view. view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) view.setContentCompressionResistancePriority(.defaultLow, for: .vertical) view.setContentHuggingPriority(.required, for: .horizontal) view.setContentHuggingPriority(.required, for: .vertical) return view } func updateUIView(_ view: UIImageView, context: Context) { update(view) } func update(_ view: UIImageView) { autoreleasepool{//not working if let data = data { view.image = nil//set to nil first is not working view.image = HDRImageView.reader.image(data: data) } else { view.image = nil } view.preferredImageDynamicRange = enableHDR ? .high : .standard } } } But when I update the input data, seems that the old image data can not be freeed. After several changes, the app takes too much memory and crash. I found it's the VM:ImageIO_Surface_Data and the VM_Image_IO take up the memory. If I change the HDRImageView into a normal Image(uiimage:UIImage(data:)) It no longer have this issue. Is it a memory leak? and how to solve this. Update: I then tried using Image(_:cgImage), and it appear to be the same result.
Posted
by SpaceGrey.
Last updated
.
Post not yet marked as solved
0 Replies
126 Views
Hello We received frequent crashes for the webkit on 17.4.1. We checked the code as well nothing got changed from our side. I tried to reproduce it but unable to do so. Can anybody advice on this. Below is the stack trace for same Please help to check. Thanks in advance
Posted Last updated
.
Post not yet marked as solved
3 Replies
169 Views
Hi, The goal is the move an element based on an input matrix using timer to trigger changes in the position. Say we have 2 positions, an input matrix and the element that is to be moved defined: import SwiftUI import Foundation // Positions struct PositionConstants { static let pos_1 = CGPoint(x: 155, y: 475) static let pos_2 = CGPoint(x: 135, y: 375) } // Input Matrix struct Input { static let input_1: [[Int]] = [ [ 1, 1, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ], ] } // Element Class class Element: ObservableObject { let imageName: String let name: String let size: CGSize @Published var position: CGPoint init(imageName: String, name: String, size: CGSize, position: CGPoint) { self.imageName = imageName self.name = name self.size = size self.position = position } } Moving the element without a function works perfectly fine: struct Pos_View: View { @ObservedObject var element_1 = Element(imageName: "pic_1", name: "", size: CGSize(width: 100, height: 100), position: PositionConstants.pos_1) let Input_Matrix = Input.input_1 // Index to track current row in matrix @State private var currentIndex = 0 // Timer to trigger updates private let timer = Timer.publish(every: 1.0, on: .main, in: .common).autoconnect() var body: some View { VStack { // Display element Image(element_1.imageName) .resizable() .frame(width: element_1.size.width, height: element_1.size.height) .position(element_1.position) .onReceive(timer) { _ in // Update element position based on matrix if currentIndex < Input_Matrix.count { let isFirstElementOne = Input_Matrix[currentIndex][0] == 1 let newPosition = isFirstElementOne ? PositionConstants.pos_2 : PositionConstants.pos_1 withAnimation { element_1.position = newPosition } currentIndex += 1 } else { // Stop the timer when we reach the end of the matrix timer.upstream.connect().cancel() } } } } } struct ContentView: PreviewProvider { static var previews: some View { Pos_View() } } But when using a function to trigger the animation, I get the error "Cannot use mutating member on immutable value: 'self' is immutable" when calling the function using a button: struct Pos_View: View { @ObservedObject var element_1 = Element(imageName: "pic_1", name: "", size: CGSize(width: 100, height: 100), position: PositionConstants.pos_1) let Input_Matrix = Input.input_1 // Index to track current row in matrix @State var currentIndex = 0 // Timer to trigger updates private var timer: Timer? var body: some View { VStack { // Display element Image(element_1.imageName) .resizable() .frame(width: element_1.size.width, height: element_1.size.height) .position(element_1.position) // Button to start animation Button("Start Animation") { startAnimation() } } } mutating func startAnimation() { currentIndex = 0 // Reset index before starting animation timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) {timer in if self.currentIndex < self.Input_Matrix.count { let isFirstElementOne = self.Input_Matrix[self.currentIndex][0] == 1 let newPosition = isFirstElementOne ? PositionConstants.pos_2 : PositionConstants.pos_1 withAnimation { self.element_1.position = newPosition } self.currentIndex += 1 } else { // Stop the timer when we reach the end of matrix timer.invalidate() } } } } struct ContentView: PreviewProvider { static var previews: some View { Pos_View() } } The function is defined as mutating and the element as as @ObservedObject. Anyone has a clue?
Posted
by Heph.
Last updated
.