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

Swift Documentation

Posts under Swift tag

2,005 Posts
Sort by:
Post not yet marked as solved
2 Replies
60 Views
Hi there -- I'm cleaning up the accessibility in our app and making sure it adheres to Apple's suggested guidelines. For accessibilityHint, apple lists a couple of suggestions in the doc here: https://developer.apple.com/documentation/objectivec/nsobject/1615093-accessibilityhint Notably this one is one that I'm having to change a lot in our app: Don’t include the action type in the hint. For example, don't create hints like “Tap to play the song” or “Tapping plays the song.” However, we have some buttons that do different actions based on a double or triple tap in VoiceOver, so our hint looks something like: "Double tap to do X, Triple Tap to do Y" This violates the accessibilityHint guidelines, but I feel like changing this would mean the customer loses out on valuable information. What does apple suggest we do in this case? Thanks in advance!
Posted
by
Post not yet marked as solved
1 Replies
61 Views
I'm trying to get the same path you'd get by running getconf DARWIN_USER_CACHE_DIR in the terminal, but via FileManager.default.urls(for: , in:) , but can't really find out how is there a way to do that other than running the shell script via swift?
Posted
by
Post not yet marked as solved
2 Replies
62 Views
Gents, dev(il)s, I am looking for a piece of code or principal explanation to realise following: I have a array of struct Item{} Each item has child [Item] in the content view I would like to have a hierarchical displayed tree of my Items and for each Item line I would like to have a button to remove it or add a child item for a selected one I tired List entity, navigation and have no real success. Is anybody there to give me a small guide? Thank you M
Posted
by
Post not yet marked as solved
0 Replies
50 Views
Hello fellow developers, We are trying to develop a chatbot application for ios devices using the powers of Oracle Digital Assistant. Main Documentation :- https://docs.oracle.com/en/cloud/paas/digital-assistant/use-chatbot/oracle-ios.html Implementation instructions :- https://blogs.oracle.com/digitalassistant/post/oracle-techexchange-using-the-oracle-ios-sdk-to-integrate-oracle-digital-assistant-in-mobile-applications The point is when we are trying to run the app, we are facing tons of warnings as in below screenshot. Here is the code for the ViewController.swift as below: // // ViewController.swift // ODA_Configure // // Created by Macbook on 15/05/24. // //import UIKit // //class ViewController: UIViewController { // // override func viewDidLoad() { // super.viewDidLoad() // // Do any additional setup after loading the view. // } // // //} // Import the SDK import UIKit import BotClientUISDK public class ViewController: UIViewController { // Declare a global BotsViewController variable in your app view controller class public var chatViewController: BotsViewController? public override func viewDidLoad() { super.viewDidLoad() // Obtain a shared instance of BotsViewController from BotsUIManager chatViewController = BotsUIManager.shared().viewControllerInstance() // Specify the color changes if any in a particular component. Make sure you set all the required colors in BotsProperties before adding the chat view to the view controller. // Add the chatViewController to your navigationController self.navigationController?.pushViewController(chatViewController!, animated: false) // Obtain a shared instance of BotsManager let botsManager = BotsManager.shared() // If you require access to callback methods provided in AuthenticationProvider. Make sure your class conforms to BotsMessageServiceDelegate // botsManager.authenticationTokenProvider = self let baseUrl = "idcs-oda-81e5e7409d52405784089abe830a8820-da12.data.digitalassistant.oci.oraclecloud.com" let channelID = "ff8a2d3f-7d65-4dab-a09a-d8f574ce5b7a" // Initialize a BotsConfiguration object and set feature flags if required. let botsConfiguration = BotsConfiguration(url: baseUrl , channelId: channelID) BotsManager.shared().connect(botsConfiguration: botsConfiguration) // Set the feature flag values if the desired values are different from the default values botsConfiguration.showConnectionStatus = true botsConfiguration.enableSpeechSynthesis = true botsConfiguration.disablePastActions = "none" // Initialize the configuration in botsViewController. Make sure you set all the feature flag values before passing the botsConfiguration to initConfiguration. chatViewController?.initConfiguration(botsConfiguration: botsConfiguration) // If you require access to callback methods provided in BotsMessageServiceDelegate. Make sure your class conforms to BotsMessageServiceDelegate //botsManager.delegate = self // If you require access to callback methods provided in BotsEventListener. Make sure your class conforms to BotsEventListener //botsManager.botsEventListener = self // Initialize and establish connection to the chat server BotsManager.shared().initialize(botsConfiguration: botsConfiguration, completionHandler: { (connectionStatus, error) in if error != nil { print ("Error: \(String(describing: error?.localizedDescription))") } else { print ("Connection Status: \(connectionStatus)") } }) } } After executing this code, we are getting the message as build succeeded , and this is the emulator, which happens to be blank white all the time. Possibly due the warning which I have posted above this seems to be the showstopper in the development. We are developing this for a prestigious client and would request an assistance as soon as possible. P.S :- We are using Xcode 15 with Simulator of version 17.0.
Posted
by
Post not yet marked as solved
2 Replies
93 Views
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
Posted
by
Post not yet marked as solved
0 Replies
60 Views
Hello! I want to create an indoor mapping application in Swift, using the LiDAR scanner. I searched among frameworks and I found that ARKit, RealityKit and RoomPlan would be useful. Which is the proper way to create a 2D indoor mapping app? And which is the proper way to create a 3D indoor mapping app? Are there any modifications I have to make on my code in order to have both?
Posted
by
Post not yet marked as solved
0 Replies
39 Views
Hi, I have been receiving an email error message: ITMS-90426: Invalid Swift Support - The SwiftSupport folder is missing. Rebuild your app using the current public (GM) version of Xcode and resubmit it. when submitting an app to the App Store Connect using xcode. I have searched for many solutions online, but none of them have worked. Later, I manually created the SwiftSupport directory and copied the Swift dynamic library (dylib) that the app depends on to this directory, as well as copying them to the. app/Frameworks directory. After submitting, I received an email saying that these. dylib dynamic libraries are not in the. app/Frameworks directory. I opened the IPA file and checked the directory, and I really saw that they are located below. I don't know where the problem is, can you tell me the exact reason?
Posted
by
Post not yet marked as solved
2 Replies
127 Views
I've been encountering a strange crash that occurs randomly on my app's startup. The app compiles and (usually) runs just fine but every so often will close out immediately within a second or two of launching. I have found no methods to consistently reproduce this crash. Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x0000000000000000, 0x0000000000000000 Termination Reason: SIGNAL 6 Abort trap: 6 Last Exception Backtrace: 0 CoreFoundation 0x1a5498870 __exceptionPreprocess + 164 1 libobjc.A.dylib 0x19d7fbc00 objc_exception_throw + 60 2 CoreFoundation 0x1a551d4f8 -[NSException init] + 0 3 Foundation 0x1a439877c -[NSObject(NSKeyValueCoding) setValue:forKey:] + 284 4 UIKitCore 0x1a796b188 -[UIViewController setValue:forKey:] + 80 5 UIKitCore 0x1a796b10c -[UIRuntimeOutletConnection connect] + 84 I would include the full crash report but for the URL needed for file attachments contains sensitive language somehow?? Any help resolving this issue would be greatly appreciated.
Posted
by
Post not yet marked as solved
0 Replies
79 Views
I've been encountering a strange crash that occurs randomly on my app's startup. The app compiles and (usually) runs just fine. I have found no methods to consistently reproduce this crash. I would provide the exception backtrace, but for some reason it's being flagged as sensitive language?? So instead I've attached the full crash log for anyone who is interested. Any help resolving this issue would be greatly appreciated.
Posted
by
Post not yet marked as solved
0 Replies
59 Views
Hello, I'm facing an issue with the volume slider in AVPlayer. Despite setting the volume property and mute property to false, the volume slider does not work as expected. Initially, the volume is muted with the slider set to the minimum. If I change the volume, when I release the slider, it returns to the minimum and the mute icon remains active. However, if I set it to maximum, the setting remains and the icon changes. However, the video volume never changes and remains at the value set in the code. Here is the code I am using: var player: AVPlayer! var playerController: AVPlayerViewController! override func viewDidLoad() { super.viewDidLoad() player = AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: "video", ofType: "mp4")!)) player.volume = 0.5 player.isMuted = false playerController = AVPlayerViewController() playerController.player = player playerController.view.frame = self.view.frame addChild(playerController) view.addSubview(playerController.view) playerController.view.frame = view.bounds playerController.didMove(toParent: self) player.play() } Can someone please help me resolve this issue? Any assistance would be greatly appreciated. Thank you.
Posted
by
Post not yet marked as solved
2 Replies
122 Views
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unsupported object <CPActionSheetTemplate: 0x600000883720> <identifier: 154853B1-42C9-4A2E-A2AA-8431664FCDC4, userInfo: (null), tabTitle: (null), tabImage: (null), showsTabBadge: 0> passed to presentTemplate:animated:completion:. Allowed classes: {( CPGridTemplate, CPListTemplate, CPNowPlayingTemplate, CPTabBarTemplate, CPAlertTemplate, CPVoiceControlTemplate )} Thanks in advance!
Posted
by
Post not yet marked as solved
0 Replies
58 Views
Problem Statement: Unable to import .h file from an ObjC SPM to a .h file in an ObjC file in a framework with mix of ObjC and Swift code The issue is: in order to support access of ObjC file in Swift code in a framework we need to use umbrella header (in place of bridging header). Once the file is imported in Umbrella header and made public it will no longer allow import of .h file from package in its interface Project Structure: a. Package: ObjCPackage ObjCPackage |- Package.swift |- ObjCPackage MathsUtilities.h (class interface) MathsUtilities.m (class implementation) NiceLogs.h (protocol) b. Project: ObjCSwiftFramework ObjCSwiftFramework |- ObjCSwiftFramework.h (umbrella header) |- Calculation.h (objc class interface) |- Calculation.m (objc class implementation) |- SwiftCalci.swift (swift class) Details: #import <ObjCSwiftFramework/Calculation.h> added in ObjCSwiftFramework.h as Calculation has to be used in SwiftCalci Calculation.h marked as public in target membership in Xcode so that it can be added in umbrella header ObjCSwiftFramework.h #import "NiceLogs.h" in Calculation.h gives error Here is a small sample which I created to demonstrate the problem: ObjCSwiftFramework
Posted
by
Post marked as solved
1 Replies
93 Views
I am trying to launch openImmersiveSpace, but seem like there is an issue with the openImmersiveSpace Task. Error: Static method 'buildExpression' requires that 'Task<OpenImmersiveSpaceAction.Result, Never>' conform to 'View' Here is the code and the error shows up on the "Task" line. import SwiftUI import RealityKit import RealityKitContent struct TestView: View { @Environment(\.openImmersiveSpace) var openImmersiveSpace @Environment(\.dismissImmersiveSpace) var dismissImmersiveSpace var body: some View { VStack{ Text("Open Full Immersive & switch to NextViewArea") NavigationLink { Task { await openImmersiveSpace(id: "ImmersiveSpace") } NextViewArea() } label:{ Label(" Enter Full Immersive Space") } } } } How can I move onto the next view area in the floating window while also launching full immersive space. Any help would be much appreciated.
Posted
by
Post not yet marked as solved
0 Replies
96 Views
I have encountered a strange behavior these past couple weeks while dealing with Bluetooth, mostly because my code hasn't changed in over 6 months (maybe it was not working before and now it's correct, who knows). Essentially, when i pair with a bluetooth device for the first time, the onchange has stopped firing. I can post more exact code of the view but I didn't think it was necessary but after you select the device you want to connect to (for the first time) you get asked by the OS to pair. After successful connection, we read information from the device (the Profiles). Once I get that information, i set dataGathered to true which triggers .onChange and I can navigate. However, with this initial connection/pairing the .onChange is never triggered, but i know i'm getting my dataGathered set to true because my print is being set. Subsequent connections do cause .onChange to be triggered with 0 profiles and with many profiles. This code hasn't changed in months so i'm not sure if there's SwiftUI bug that's sprung up or what, or if there's an inherint issue with what i was doing and it's only now being caught. struct DeviceSearchView: View { @StateObject var connectedManager: Manager = Manager() @StateObject var bluetoothListener: Listener = BluetoothListener() var body: some View { body .onChange(self.bluetoothListener.connectedDevice) { device in device.getData() } .onChange(self.connectedManager.dataGathered) { dataGathered in // determine navigation } } } Manager Object final class Manager: ObservedObject, BTDelegate, Identifiable /*i've tried adding/switching with Equatable but no change*/ { @Published var dataGathered: Bool = false @Published var profileList: Profile = [Profile]() @Published var index: Int = 0 func updatedProfile(list: NSArray, selectedIndex: Int) { print("profiles are in fact here") var newList = [Profile]() for element in list { if let profile = element as? B50Profile { print("\(profile.name)") if !newList.contains(profile){ newList.append(profile) } } } self.profileList = newList self.index = selectedIndex self.dataGathered = true print("data gathered is \(self.dataGathered)" } }
Posted
by
Post not yet marked as solved
0 Replies
82 Views
I'm developing an app with a chart in SwiftUI. I want the following block of code to run when the chart is clicked. On my personal iPhone, the app works flawlessly. But when I try it in the simulator it crashes and gives me about 5-10 of the following errors. When I remove the @Query macro from the code block, the application does not crash in the simulator, but I continue to get the errors I mentioned. If I do not run the following code block, I do not get the errors I mentioned. struct SaleDetailView: View { @Query(filter: #Predicate<Registration> { !$0.activeRegistration }) private var regs: [Registration] var body: some View { VStack { DailySaleView() } .padding() } } Thank you in advance for your answers. Do not hesitate to ask if you have any questions. Thanks, MFS
Posted
by
Post not yet marked as solved
0 Replies
59 Views
I have implemented NFC card reading functionality using NFCTagReaderSession. After starting the NFC reader session in landscape mode at least once, if I switch back to portrait mode and attempt to start the NFC reader session again, the scanning sheet does not respond to any touch interactions. Regardless of whether the screen is rotated, I expect the user to be able to close the reading screen, but it remains open. Is there any workaround for this issue? Code: class ViewController: UIViewController, NFCTagReaderSessionDelegate { func tagReaderSessionDidBecomeActive(_ session: NFCTagReaderSession) { } func tagReaderSession(_ session: NFCTagReaderSession, didInvalidateWithError error: any Error) { } func tagReaderSession(_ session: NFCTagReaderSession, didDetect tags: [NFCTag]) { } override func viewWillTransition(to size: CGSize, with coordinator: any UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) let session = NFCTagReaderSession(pollingOption: [.iso14443], delegate: self) session?.begin() } } PLATFORM AND VERSION iOS Device Information: Xcode 15.3 iPhone Xs (iOS 17.4) iPhone 8 (iOS 16.7.7) STEPS TO REPRODUCE Procedure and Results: 1.Launch the app. →The portrait mode is displayed. 2.Rotate from portrait to landscape. →The landscape screen shows the NFC reading interface. 3.Tap the cancel button on the NFC reading screen. →The landscape NFC reading screen closes. 4.Rotate back from landscape to portrait. →The portrait screen displays the NFC reading interface. 5.Tap the cancel button (cross icon) on the NFC reading screen. →The portrait NFC reading screen does not close.
Posted
by
Post not yet marked as solved
0 Replies
98 Views
Hello, fairly new to Swift, I come from a React Native background. One of the hardest things I'm finding is simply customising the screen headers in the navigation. I've managed to do it using a custom modifier that uses .toolbar and ToolbarItem as shown below: struct NavBar: ViewModifier { let title: String let showBackButton: Bool? @Environment(\.dismiss) private var dismiss func body(content: Content) -> some View { return content .toolbar { if showBackButton == true { ToolbarItemGroup(placement: .navigationBarLeading) { Button(action: { dismiss() }) { Image("BackButton") }.padding(.top, 18) } } ToolbarItem(placement: .principal) { Text(title) .font(Font.custom("Knight Vision", size: 28)) .foregroundColor(.white).padding(.top, 20) } } .navigationBarBackButtonHidden(true) } } This is all fine and suits my needs however I'm finding that the toolbar does not slide in with the rest of the screen when navigating to as screen with it on. I would expect the title to slide in with the other items on the screen. Especially since the toolbar does animate out, it just does not animate in. Heres a video so you can see what I mean. Am I doing something wrong here? Is there a better way to do this? [linkText](https://www.youtube.com/shorts/6M-glapBZz0 /)
Posted
by
Post not yet marked as solved
1 Replies
120 Views
Preface Upon rotating the interface, the UICollectionViewCells overlap, generating an unpleasant animation that for sure can't be used in production. The code The code was executed on iPhone 6S (NN0W2TU/A A1688) with iOS 15.8.2. I could reproduce the issue on iPhone 15 Pro with iOS 17 on simulator as well. SelfConfiguringCell.swift: import UIKit protocol SelfConfiguringCell: UICollectionViewCell { static var reuseIdentifier: String { get } func configure(with image: String) } ISVImageScrollView.swift: Code here CarouselCell.swift: import UIKit import SnapKit class CarouselCell: UICollectionViewCell, SelfConfiguringCell, UIScrollViewDelegate { static var reuseIdentifier: String = "carousel.cell" internal var image: String = "placeholder" { didSet { self.imageView = UIImageView(image: UIImage(named: image)) self.scrollView.imageView = self.imageView } } let scrollView: ISVImageScrollView = { let scrollView = ISVImageScrollView() scrollView.minimumZoomScale = 1.0 scrollView.maximumZoomScale = 30.0 scrollView.zoomScale = 1.0 scrollView.contentOffset = .zero scrollView.bouncesZoom = true return scrollView }() var imageView: UIImageView = { let image = UIImage(named: "placeholder")! let imageView = UIImageView(image: image) return imageView }() func setImage(_ image: String) { self.image = image } func configure(with image: String) { self.setImage(image) self.scrollView.snp.makeConstraints { make in make.left.top.right.bottom.equalTo(contentView) } } override init(frame: CGRect) { super.init(frame: frame) contentView.backgroundColor = UIColor.black scrollView.delegate = self scrollView.imageView = self.imageView contentView.addSubview(scrollView) } required init?(coder: NSCoder) { fatalError("Cannot init from storyboard") } func viewForZooming(in scrollView: UIScrollView) -> UIView? { return self.imageView } } ViewController: import UIKit class ViewController: UICollectionViewController { var currentPage: IndexPath? = nil let images = ["police", "shutters", "depot", "cakes", "sign"] init() { let compositionalLayout = UICollectionViewCompositionalLayout { sectionIndex, environment in let absoluteW = environment.container.effectiveContentSize.width let absoluteH = environment.container.effectiveContentSize.height // Handle landscape if absoluteW > absoluteH { print("landscape") let itemSize = NSCollectionLayoutSize( widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1) ) let item = NSCollectionLayoutItem(layoutSize: itemSize) let groupSize = NSCollectionLayoutSize( widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1) ) let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item]) let section = NSCollectionLayoutSection(group: group) return section } else { // Handle portrait print("portrait") let itemSize = NSCollectionLayoutSize( widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(absoluteW * 9.0/16.0) ) let item = NSCollectionLayoutItem(layoutSize: itemSize) let groupSize = NSCollectionLayoutSize( widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(absoluteW * 9.0/16.0) ) let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item]) let section = NSCollectionLayoutSection(group: group) return section } } let config = UICollectionViewCompositionalLayoutConfiguration() config.interSectionSpacing = 0 config.scrollDirection = .horizontal compositionalLayout.configuration = config super.init(collectionViewLayout: compositionalLayout) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() collectionView.delegate = self collectionView.dataSource = self collectionView.isPagingEnabled = true // Register cell for reuse collectionView.register(CarouselCell.self, forCellWithReuseIdentifier: CarouselCell.reuseIdentifier) } override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.images.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let reusableCell = collectionView.dequeueReusableCell(withReuseIdentifier: CarouselCell.reuseIdentifier, for: indexPath) as? CarouselCell else { fatalError() } let index : Int = (indexPath.section * self.images.count) + indexPath.row reusableCell.configure(with: self.images[index]) return reusableCell } } Notes I found a similar unanswered question here. I'm sure something can be done about it because if I switch to SwiftUI with a TabView, that according to SwiftUI Introspect documentation for TabViewWithPageStyleType, is using UICollectionView under the hood, I'm not getting that ugly animation anymore. Though I can't switch to SwiftUI to use TabView because on interface rotation it loses the page index (well known bug, see here), which probably is even trickier to workaround.
Posted
by
Post not yet marked as solved
0 Replies
144 Views
Hi, I try to create some machine learning model for each stock in S&P500 index. When creating the model(Boosted tree model) I try to make it more successfully by doing hyper parameters using GridSearchCV. It takes so long to create one model so I don't want to think of creating all stocks models. I tried to work with CreateML and swift but it looks like it takes longer to run than sklearn on python. My question is how can I make the process faster? is there any hyper parameters on CreateML on swift (I couldn't find it at docs) and how can I run this code on my GPU? (should be much faster).
Posted
by