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

Swift Documentation

Posts under Swift tag

2,015 Posts
Sort by:
Post not yet marked as solved
2 Replies
124 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 mabubakar.
Last updated
.
Post not yet marked as solved
1 Replies
131 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 Last updated
.
Post not yet marked as solved
0 Replies
114 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 tonygo.
Last updated
.
Post not yet marked as solved
0 Replies
87 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 miguelg97.
Last updated
.
Post marked as solved
3 Replies
130 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 Last updated
.
Post not yet marked as solved
2 Replies
136 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 Last updated
.
Post marked as solved
1 Replies
91 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 Last updated
.
Post not yet marked as solved
0 Replies
58 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 Last updated
.
Post not yet marked as solved
6 Replies
167 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 mabubakar.
Last updated
.
Post not yet marked as solved
1 Replies
124 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 Last updated
.
Post not yet marked as solved
0 Replies
115 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 davidesq.
Last updated
.
Post not yet marked as solved
0 Replies
99 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 Sneha0110.
Last updated
.
Post not yet marked as solved
1 Replies
160 Views
Is the timeout for session-level authentication challenge handling documented somewhere? For example, if I get the urlSession(_:didReceive:) callback for server trust authentication, how long do I have to invoke the completion handler (or return from the callback if using Swift Concurrency)? Or is this completely dependent on the server's settings?
Posted
by Aqua_Geek.
Last updated
.
Post not yet marked as solved
0 Replies
131 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 rolson.
Last updated
.
Post not yet marked as solved
1 Replies
259 Views
@Query(filter: #Predicate<Note>{ note in note.isDeleted == false && (note.title != "" || note.content != "") } ,sort: [SortDescriptor(\Note.isPinned, order: .reverse),SortDescriptor(\Note.createdAt, order: .reverse)] , animation: .smooth(duration: 0.3) ) private var notes: [Note] if I delete filter part navigationLink works properly
Posted
by AzizK.
Last updated
.
Post marked as solved
4 Replies
209 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
91 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 Last updated
.
Post not yet marked as solved
0 Replies
89 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 2018code.
Last updated
.