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

Swift Documentation

Posts under Swift tag

2,001 Posts
Sort by:
Post marked as solved
2 Replies
76 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 italom.
Last updated
.
Post not yet marked as solved
1 Replies
31 Views
I have an extremely straightforward situation where an @IBOutlet in a ViewController is connected to a property in an XIB file. I've been working with iOS apps for more than ten years, and done this about a million times. For some reason, the property becomes nil at some point after the view is loaded. I can check with the debugger to see that it is not nil at viewDidLoad, and there is nothing in my code that sets it to anything else. I added a custom setter and getter to the variable so that I could stop in the debugger when it gets set, and the setter only gets called once, with a non-nil value. I suspect that somehow, a different copy of my ViewController is getting instantiated, but when it does, there are no calls to any of the usual methods like viewDidLoad. In fact there is not even a call to the init method. I don't understand how this is possible.
Posted
by flarosa.
Last updated
.
Post not yet marked as solved
0 Replies
20 Views
Hi, I am new to Swift and would like to write a simple Swift script to show some HDR images or video on my VisionPro. I tried to find some code online as shown in the attachment to put one HDR image and one SDR side by side, but it seems like not to take any HDR effect. Thanks in advance.
Posted Last updated
.
Post not yet marked as solved
1 Replies
28 Views
I am little confused about when to use State / StateObject / ObservedObject. What I have researched and what I understand: @State --> for value types @StateObject --> for reference types @ObservedObject --> child objects who needs reference to above two (the parent object should have @State/@StateObject and the object should conform to Observable) I am clear about Environment object.
Posted Last updated
.
Post not yet marked as solved
5 Replies
84 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 Last updated
.
Post not yet marked as solved
1 Replies
426 Views
In our app, we needed to use visionkit framework to lift up the subject from an image and crop it. Here is the piece of code: if #available(iOS 17.0, *) { let analyzer = ImageAnalyzer() let analysis = try? await analyzer.analyze(image, configuration: self.visionKitConfiguration) let interaction = ImageAnalysisInteraction() interaction.analysis = analysis interaction.preferredInteractionTypes = [.automatic] guard let subject = await interaction.subjects.first else{ return image } let s = await interaction.subjects print(s.first?.bounds) guard let cropped = try? await subject.image else { return image } return cropped } But the s.first?.bounds always returns a cgrect with all 0 values. Is there any other way to get the position of the cropped subject? I need the position in the image from where the subject was cropped. Can anyone help?
Posted
by utshas.
Last updated
.
Post not yet marked as solved
3 Replies
119 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 Last updated
.
Post not yet marked as solved
3 Replies
140 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 Last updated
.
Post not yet marked as solved
0 Replies
45 Views
Hello, I am developing a private internal Flutter app for our customer, which will not be published on the Apple Store. One of the key features of this app is to collect RF strength metrics to share user experience with the network. For Android, we successfully implemented the required functionality and are able to collect the following metrics: Signal strength level (0-4) Signal strength in dBm RSSI RSRQ Cell ID Location Area Code Carrier name Mobile country code Mobile network code Radio access technology Connection status Duplex mode However, for iOS, we are facing challenges with CoreTelephony, which is not returning the necessary data. We are aware that CoreTelephony is deprecated and are looking for alternatives. We noticed that a lot of the information we need is available via FTMInternal-4. Is there a way to access this data for a private app? Are there any other recommended approaches or frameworks that can be used to gather cellular network information on iOS for an app that won't be distributed via the Apple Store? my swift code import Foundation import CoreTelephony class RfSignalStrengthImpl: RfSignalStrengthApi { func getCellularSignalStrength(completion: @escaping (Result<CellularSignalStrength, Error>) -> Void) { let networkInfo = CTTelephonyNetworkInfo() guard let carrier = networkInfo.serviceSubscriberCellularProviders?.values.first else { completion(.failure(NSError(domain: "com.xxxx.yyyy", code: 0, userInfo: [NSLocalizedDescriptionKey: "Carrier not found"]))) return } let carrierName = carrier.carrierName ?? "Unknown" let mobileCountryCode = carrier.mobileCountryCode ?? "Unknown" let mobileNetworkCode = carrier.mobileNetworkCode ?? "Unknown" let radioAccessTechnology = networkInfo.serviceCurrentRadioAccessTechnology?.values.first ?? "Unknown" var connectionStatus = "Unknown" ... ... } Thank you for your assistance.
Posted
by raiton.
Last updated
.
Post not yet marked as solved
2 Replies
67 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 wilc0.
Last updated
.
Post not yet marked as solved
4 Replies
253 Views
Hello developers ! I've created a List or a ForEach from a binding where there are TextFields or TextEditors inside. When I go to fill in the text, the keyboard dismisses after one char is typed in ! My need is to be able to add textfields as much as required. Please have a look to this code import SwiftUI struct ContentView: View { @State private var messages = ["Hello 1","Hello 2","Hello 3"] var body: some View { VStack(alignment: .leading) { List($messages, id: \.self) { $msg in TextEditor(text: $msg) } ForEach($messages, id: \.self) { $msg in VStack{ TextEditor(text: $msg) } .contextMenu{ Button(role: .destructive, action: { messages = messages.filter {$0 != msg} }, label:{ Text("Delete entry") }) } } Button(action: { messages.append("-") } , label: { Text("Add a row") }) } .background(.black) .padding() } } #Preview { ContentView() } I'm using iOS 17.4 and Xcode 15.3 Thanks !
Posted
by boujouman.
Last updated
.
Post not yet marked as solved
0 Replies
58 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 Last updated
.
Post not yet marked as solved
0 Replies
66 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 Louiza123.
Last updated
.
Post not yet marked as solved
0 Replies
50 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 forchen.
Last updated
.
Post not yet marked as solved
0 Replies
83 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 Last updated
.
Post not yet marked as solved
0 Replies
65 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 Luck81.
Last updated
.
Post marked as solved
2 Replies
129 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 Last updated
.
Post not yet marked as solved
1 Replies
884 Views
I get this error while migrating from ObservableObject to @Observable. Call to main actor-isolated initializer 'init()' in a synchronous nonisolated context My original code: struct SomeView: View { @StateObject private var viewModel = ViewModel() } After migration: @MainActor @Observable class BaseViewModel { } @MainActor class ViewModel: BaseViewModel { } struct SomeView: View { @State private var viewModel = ViewModel() } As discussed here. It seems like @StateObject is adding @MainActor compliance to my View under the hood because it's wrappedValue and projectedValue properties are marked as @MainActor, while on @State they are not. @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) @frozen @propertyWrapper public struct StateObject&lt;ObjectType&gt; : DynamicProperty where ObjectType : ObservableObject { ... @MainActor public var wrappedValue: ObjectType { get } .... @MainActor public var projectedValue: ObservedObject&lt;ObjectType&gt;.Wrapper { get } } One solution for this is to mark my View explicitly as @MainActor struct ViewModel: View but it have it side effects, for example code like: Button(action: resendButtonAction) { Text(resendButtonAttributedTitle()) } Will result a warning Converting function value of type '@MainActor () -&gt; ()' to '() -&gt; Void' loses global actor 'MainActor' While could be easily solved by using instead Button(action: { resendButtonAction() } ) { Text(resendButtonAttributedTitle()) } I still feel like marking the whole View explicitly as @MainActor is not a good practice. Adding fake @StateObject property to my view also do the trick, but it's a hack (the same for @FetchRequest). Can anyone think of a more robust solution for this?
Posted
by itayAm.
Last updated
.
Post not yet marked as solved
0 Replies
59 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 Last updated
.
Post marked as solved
3 Replies
1k Views
Hi -- I am attempting to use C++ and Swift in a single project but I am struggling with finding the proper way to do this. Ideally I want to have both my C++ and Swift code in the same project and not use a framework to keep them separate. As an example, how would I create an object of the following C++ class: class Foo { public: Foo() { // do stuff } } From what I read, it should be as simple as this: let foo = Foo() But Xcode says it Cannot find 'Foo' in scope. How do I import Foo into my Swift code? Is there a project setting that needs to be changed to automatically make my C++ classes available? Or do I need to create a Clang module (as described in this page: https://www.swift.org/documentation/cxx-interop/#importing-c-into-swift) to expose the C++ code to Swift? If so, where in my Xcode project should that go? I am using Xcode 15.2 on macOS 14.2.1. I have also set the C++ and Objective-C Interoperability setting for my project to C++/Objective-C++.
Posted
by dpm.
Last updated
.