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

Swift Documentation

Posts under Swift tag

2,026 Posts
Sort by:
Post not yet marked as solved
0 Replies
26 Views
I was following the Swiftui tutorial at section 6 (https://developer.apple.com/tutorials/swiftui/creating-and-combining-views) to use a circle image to create an overlapping effect on the map. Turns out that when using a GeometryReader, the bottom padding was not working at all: VStack{ MapView().frame(height:300) CircleImage() .offset(y: -130) .padding(.bottom, -130) VStack(alignment:.leading){ Text( "Turtle Rock" ) .font( .title ) HStack { Text( "Joshua Tree National Park" ) .font( .subheadline ) Spacer() Text( "California" ) .font( .subheadline ) } }.padding(/*@START_MENU_TOKEN@*/10/*@END_MENU_TOKEN@*/) } This is the code for the CicleImage view: GeometryReader(content: { geometry in let _ = print( geometry.size.width ) AsyncImage( url: URL( string: "https://cms.rationalcdn.com/v3/assets/blteecf9626d9a38b03/bltf5486c52361f2012/6144fafd39dff133fc23de9f/img-ios.png" ) ) .frame(width: geometry.size.width) .clipShape( Circle() ).overlay{ Circle().stroke( .white, lineWidth: 4 ) }.shadow( radius: 7 ) })
Posted
by
Post not yet marked as solved
3 Replies
91 Views
I just purchased a new M3 chip MacBook Air a little after it came out. I was able to create and deploy an iOS application. However, now that I am trying to create a new project Xcode throws an error upon launch. Steps to recreate the error (if possible) Open Xcode Select create new app An error is where the preview should be. At this point I have added no code. It is all boiler plate from Apple.
Posted
by
Post not yet marked as solved
2 Replies
95 Views
Hello. I've been looking all over this forum and stack and done some internet searches but unfortunately have found nothing to assist in fixing an error I'm receiving on my project in Xcode. Every view shows an error identical to the one shown above, only with that specific file name displayed instead. When I go to fix the error, this is the error detail displayed: == PREVIEW UPDATE ERROR: LinkDylibError: Failed to build TabBar.swift Linking failed: linker command failed with exit code 1 (use -v to see invocation) ld: warning: search path '/Applications/Xcode.app/Contents/SharedFrameworks-iphonesimulator' not found ld: unsupported mach-o filetype (only MH_OBJECT and MH_DYLIB can be linked) in '/Users/brycemchose/Library/Developer/Xcode/DerivedData/Service_Square_App-dnblqgabcrxprhaizjtkcvouyzln/Build/Intermediates.noindex/Previews/iphonesimulator/Service Square App/Products/Debug-iphonesimulator/Service Square.app/Service Square' clang: error: linker command failed with exit code 1 (use -v to see invocation) Note that I can run the app successfully to a simulator or to my iPhone, but cannot see the preview within the Xcode canvas. I've been blindly developing the last two app updates, pushing the changes to the simulator and then tweaking the code based on the simulated version. I can keep doing this for a little while but it is significantly slower and more difficult, especially to fix small bugs and make tiny changes, so I'd really like to see if anyone has an idea for how I can get the preview back to being properly displayed. I'm brand new to this whole thing and have no idea how to fix this issue, so I'd be really grateful if someone with more experience could offer some suggestions! Thanks in advance! :)
Posted
by
Post marked as solved
1 Replies
63 Views
I'm writing a SpriteKit game in Swift that does this familiar dance in my GameScene touchesEnded(...)... let touch = touches.first!.location(in: self) let nodes = self.nodes(at: touch) ...but sometimes when the game is running, the nodes collection is empty, even though there are clearly, visibly nodes under the touch. All of the nodes I care about are children of a single SKNode, MapNode, that is one of two children of the GameScene. After a bunch of debugging, I've noticed that when this problem happens, something is causing calculateAccumulatedFrame() to return a frame that is way, way smaller than the real bounds of MapNode. When the scene begins, calculateAccumulatedFrame() is perfect, but something that happens later on breaks it. I've tried adding a node to MapNode that is the correct size to 'force' calculateAccumulatedFrame to do the right thing, but this doesn't work. Is there something obvious I am doing wrong, or some common pitfalls? Is there some way to force calculateAccumulatedFrame to return this correct size?
Posted
by
Post not yet marked as solved
0 Replies
65 Views
Hi People :) I'm experimenting with Swift/C++ interoperability these days. I'd like to understand how could I conform a Swift class to Cxx header: Like this: import Application class App: Application { public func run() { let app = NSApplication.shared let delegate = AppDelegate() app.delegate = delegate app.run() } } But I got this error: /Users/tonygo/oss/native-research/App.swift:27:7: error: inheritance from non-protocol, non-class type 'Application' class App: Application { ^ ninja: build stopped: subcommand failed. That seems normal indeed. Reproductible example: https://github.com/tony-go/native-research/tree/conform-swift-to-cxx-header (Just run make) I also have another branch on that repo where I use an intermediate Cxx bridge file that conforms to the :Application class and use the Swift API, like this: https://github.com/tony-go/native-research/tree/main/app Bit I think that its a lot of boilerplate. So I wonder which approach could I take for this? Cheers :)
Posted
by
Post not yet marked as solved
0 Replies
36 Views
I want to change the display language, particularly for week and the year and date on MultiDatePicker. By adjusting the locale, the year and date can be changed. However, I'm unable to change the display for week . I've tried several methods, such as setting the calendar and adjusting the time zone, but none of them seem to work. Are there any good way to solve it?
Posted
by
Post not yet marked as solved
1 Replies
84 Views
Summary Hello Apple Developers, I've made a custom UITableViewCell that includes a UITextField and UILabel. When I run the simulation the UITableViewCells pop up with the UILabel and the UITextField, but the UITextField isn't clickable so the user can't enter information. Please help me figure out the problem. Thank You! Sampson What I want: What I have: Screenshot Details: As you can see when I tap on the cell the UITextField isn't selected. I even added placeholder text to the UITextField to see if I am selecting the UITextField and the keyboard just isn't popping up, but still nothing. Relevant Code: UHTextField import UIKit class UHTextField: UITextField { override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } convenience init(placeholder: String) { self.init(frame: .zero) self.placeholder = placeholder } private func configure() { translatesAutoresizingMaskIntoConstraints = false borderStyle = .none textColor = .label tintColor = .blue textAlignment = .left font = UIFont.preferredFont(forTextStyle: .body) adjustsFontSizeToFitWidth = true minimumFontSize = 12 backgroundColor = .tertiarySystemBackground autocorrectionType = .no } } UHTableTextFieldCell import UIKit class UHTableTextFieldCell: UITableViewCell, UITextFieldDelegate { static let reuseID = "TextFieldCell" let titleLabel = UHTitleLabel(textAlignment: .center, fontSize: 16, textColor: .label) let tableTextField = UHTextField() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) configure() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func set(title: String) { titleLabel.text = title tableTextField.placeholder = "Enter " + title } private func configure() { addSubviews(titleLabel, tableTextField) let padding: CGFloat = 12 NSLayoutConstraint.activate([ titleLabel.centerYAnchor.constraint(equalTo: centerYAnchor), titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: padding), titleLabel.heightAnchor.constraint(equalToConstant: 20), titleLabel.widthAnchor.constraint(equalToConstant: 80), tableTextField.centerYAnchor.constraint(equalTo: centerYAnchor), tableTextField.leadingAnchor.constraint(equalTo: titleLabel.trailingAnchor, constant: 24), tableTextField.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -padding), tableTextField.heightAnchor.constraint(equalToConstant: 20) ]) } } LoginViewController class LoginViewController: UIViewController, UITextFieldDelegate { let tableView = UITableView() let loginTableTitle = ["Username", "Password"] override func viewDidLoad() { super.viewDidLoad() configureTableView() updateUI() createDismissKeyboardTapGesture() } func createDismissKeyboardTapGesture() { // create the tap gesture recognizer let tap = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing)) // add it to the view (Could also add this to an image or anything) view.addGestureRecognizer(tap) } func configureTableView() { view.addSubview(tableView) tableView.layer.borderWidth = 1 tableView.layer.borderColor = UIColor.systemBackground.cgColor tableView.layer.cornerRadius = 10 tableView.clipsToBounds = true tableView.rowHeight = 44 tableView.delegate = self tableView.dataSource = self tableView.translatesAutoresizingMaskIntoConstraints = false tableView.removeExcessCells() NSLayoutConstraint.activate([ tableView.topAnchor.constraint(equalTo: loginTitleLabel.bottomAnchor, constant: padding), tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: padding), tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -padding), tableView.heightAnchor.constraint(equalToConstant: 88) ]) tableView.register(UHTableTextFieldCell.self, forCellReuseIdentifier: UHTableTextFieldCell.reuseID) } func updateUI() { DispatchQueue.main.async { self.tableView.reloadData() self.view.bringSubviewToFront(self.tableView) } } } extension LoginViewController: UITableViewDelegate, UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: UHTableTextFieldCell.reuseID, for: indexPath) as! UHTableTextFieldCell let titles = loginTableTitle[indexPath.row] cell.set(title: titles) cell.titleLabel.font = UIFont.systemFont(ofSize: 16, weight: .bold) cell.tableTextField.delegate = self return cell } } Again thank you all so much for your help. If you need more clarification on this let me know.
Posted
by
Post not yet marked as solved
0 Replies
81 Views
On android there is a way for my app to know when the device has been restarted or powered up after a restart or powering off. I wonder if there is a way to listen for the restart/power up even on the iphone and the Apple Watch?
Posted
by
Post not yet marked as solved
0 Replies
42 Views
Hi, Using iOS 17.2 trying to build an ios app with Content Filter Network extension. My problem is that when I build it on a device and go to Settings --> VNP & Device Management the Content Filter with my identifier is showing BUT is shows invalid. Appname is Privacy Monitor and Extension name is Social Filter Control Here is is my code `// // PrivacyMonitorApp.swift import SwiftUI @main struct PrivacyMonitorApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { WindowGroup { ContentView() } } } import NetworkExtension class AppDelegate: UIResponder, UIApplicationDelegate { static private(set) var instance: AppDelegate! = nil func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { configureNetworkFilter() return true } func configureNetworkFilter() { let manager = NEFilterManager.shared() manager.loadFromPreferences { error in if let error = error { print("Error loading preferences: \(error.localizedDescription)") return } // Assume configuration is absent or needs update if manager.providerConfiguration == nil { let newConfiguration = NEFilterProviderConfiguration() newConfiguration.filterBrowsers = true newConfiguration.filterSockets = true // newConfiguration.vendorConfiguration = ["someKey": "someValue"] manager.providerConfiguration = newConfiguration } manager.saveToPreferences { error in if let error = error { print("Error saving preferences: \(error.localizedDescription)") } else { print("Filter is configured, prompt user to enable it in Settings.") } } } } } Next the FilterManager.swift `import NetworkExtension class FilterManager { static let shared = FilterManager() init() { NEFilterManager.shared().loadFromPreferences { error in if let error = error { print("Failed to load filter preferences: \(error.localizedDescription)") return } print("Filter preferences loaded successfully.") self.setupAndSaveFilterConfiguration() } } private func setupAndSaveFilterConfiguration() { let filterManager = NEFilterManager.shared() let configuration = NEFilterProviderConfiguration() configuration.username = "MyConfiguration" configuration.organization = "SealdApps" configuration.filterBrowsers = true configuration.filterSockets = true filterManager.providerConfiguration = configuration filterManager.saveToPreferences { error in if let error = error { print("Failed to save filter preferences: \(error.localizedDescription)") } else { print("Filter configuration saved successfully. Please enable the filter in Settings.") } } } } Next The PrivacyMonitor.entitlements ` The Network Extension capabilties are on and this is the SocialFilterControl `import NetworkExtension class FilterControlProvider: NEFilterControlProvider { override func startFilter(completionHandler: @escaping (Error?) -> Void) { // Initialize the filter, setup any necessary resources print("Filter started.") completionHandler(nil) } override func stopFilter(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) { // Clean up filter resources print("Filter stopped.") completionHandler() } override func handleNewFlow(_ flow: NEFilterFlow, completionHandler: @escaping (NEFilterControlVerdict) -> Void) { // Determine if the flow should be dropped or allowed, potentially downloading new rules if required if let browserFlow = flow as? NEFilterBrowserFlow, let url = browserFlow.url, let hostname = browserFlow.url?.host { print("Handling new browser flow for URL: \(url.absoluteString)") if shouldBlockDomain(hostname) { print("Blocking access to \(hostname)") completionHandler(.drop(withUpdateRules: false)) // No rule update needed immediately } else { completionHandler(.allow(withUpdateRules: false)) } } else { // Allow other types of flows, or add additional handling for other protocols completionHandler(.allow(withUpdateRules: false)) } } // Example function to determine if a domain should be blocked private func shouldBlockDomain(_ domain: String) -> Bool { // Add logic here to check the domain against a list of blocked domains let blockedDomains = ["google.com", "nu.nl"] return blockedDomains.contains(where: domain.lowercased().contains) } } And it's info.plist ` and the entitlements file ` In Xcode using automatically manage signing and both targets have the same Team Please explain the missing part
Posted
by
Post not yet marked as solved
1 Replies
96 Views
Hello everyone! I'm currently working on an iOS app developed with Swift that involves connecting to a specific bluetooth device and exchanging data even when the app is terminated or running in the background. I just want to understand why the CBCenterManager should be Implicitly unwrapped to use it. I have check out couple off apple developer sample project it was set to Implicitly unwrapped. can some one help to understand the reason behind this, also what are possible issues/scenario trigger if we set the centermanager to optional "CBcentermanager?" Thanks in Advance!
Posted
by
Post not yet marked as solved
0 Replies
99 Views
Hi everyone! We are wondering whether it's possible to have two macOS apps use the Voice Processing from Audio Engine at the same time, since we have had issues trying to do so. Specifically, our app seems to cut off the input stream from the other, only if it has Voice Processing enabled. We are developing a macOS app that records microphone input simultaneously with videoconference apps like Zoom. We are utilizing the Voice Processing from Audio Engine like in this sample: https://developer.apple.com/documentation/avfaudio/audio_engine/audio_units/using_voice_processing We have also noticed this behaviour in Safari recording audios with the Javascript Web Audio API, which also seems to use Voice Processing under the hood due to the Echo Cancellation. Any leads on this would be greatly appreciated! Thanks
Posted
by
Post not yet marked as solved
2 Replies
96 Views
Hi, I'm trying to implement a type conforming to WKScriptMessageHandlerWithReply while having Swift's strict concurrency checking enabled. It's not been fun. The protocol contains the following method (there's also one with a callback, but we're in 2024): func userContentController( controller: WKUserContentController, didReceive message: WKScriptMessage ) async -> (Any?, String?) WKScriptMessage's properties like body must be accessed on the main thread. But since WKScriptMessageHandlerWithReply is not @MainActor, neither can this method be so marked (same for the conforming type). At the same time WKScriptMessage is not Sendable, so I can't handle it in Task { @MainActor in this method, because that leads to Capture of 'message' with non-sendable type 'WKScriptMessage' in a `@Sendable` closure That leaves me with @preconcurrency import - is that the way to go? Should I file a feedback for this or is it somehow working as intended?
Posted
by
Post not yet marked as solved
0 Replies
78 Views
I have my app already in live before the privacy manifest introduced. Now, I want to migrate from cocoapods to Swift Package Manager. Will this be considered like adding the third party SDKs as new ones or will it be considered existing ones? So far I have not received any emails from Apple regarding the privacy manifest. I do not want any issues with the privacy manifest.
Posted
by
Post not yet marked as solved
1 Replies
92 Views
Hi, in my Extension FilterDataProvider class that is inherited from NEFilterDataProvider i am trying to insert logs into my CoreData entity, but when i insert it gives me error "NSCocoaErrorDomain: -513 "reason": Unable to write to file opened Readonly Any suggestions please to update the read write permission i already have tried this way but no luck let description = NSPersistentStoreDescription(url: storeURL) description.shouldInferMappingModelAutomatically = true description.shouldMigrateStoreAutomatically = true description.setOption(false as NSNumber, forKey: NSReadOnlyPersistentStoreOption) ?
Posted
by
Post not yet marked as solved
0 Replies
114 Views
I have a container view implementation that reads preference values from child views: public struct Reader<Content>: View where Content: View { public var content: () -> Content public init(@ViewBuilder content: @escaping () -> Content) { self.content = content } public var body: some View { content() .onPreferenceChange(NumericPreferenceKey.self) { value in // ... } } } This works fine until the content passed in to the container view is a Group. At that point the onPreferenceChanged modifier is applied to every child of the group, which leads to bugs in my situation. One thing I can do is simply put the content in a VStack: public var body: some View { VStack(content: content) .onPreferenceChange(NumericPreferenceKey.self) { value in // ... } } And that works fine to "Ungroup" before applying the onPreferenceChanged modifier. However, is this best practice? Is there a better way to apply a modifier to content as a whole instead of to each member of a potential group? Is it concerning that I might have an extra VStack in the view hierarchy with this fix?
Posted
by
Post not yet marked as solved
6 Replies
135 Views
Hello, i am trying to record logs in my network extension class, and then i want to read it in my application class, i.e. viewModel. However, i am unable to read the data. I have tried different ways like UserDefaults, Keychain, FileManager, NotificationCenter and CoreData. I have also used Appgroups but still there is blocker for reading data outside the scope of Extension class.
Posted
by
Post not yet marked as solved
0 Replies
84 Views
Hello, I have class file, which should save data coreData and Im only able to save data via ui. Do you have any example, how can I save data in core data via class files? Greeting Fabian
Posted
by
Post not yet marked as solved
0 Replies
80 Views
I am getting this error, only in iOS 17 (all version) on old code that had been working since iOS 15. The error occurs whenever the collectionView need to increase it's height beyond its initial height. The collectionView is inside a tableView. All autolayout constraints are set and everything use to work fine in previous version of iOS. *** Assertion failure in -[MYAPP.MYCollectionView _updateLayoutAttributesForExistingVisibleViewsFadingForBoundsChange:], UICollectionView.m:6218
Posted
by